package com.dminvoicemanager;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;

import com.dminvoicemanager.itemmaster.DM_Item_Master;
import com.dminvoicemanager.itinerary.DM_Itinerary_Report_Main;
import com.dminvoicemanager.reports.DM_Sales_Summary_Report;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class DM_InvoiceMenu extends Activity {

	// private PBDatabaseAdapter dbHelper;
	ProgressDialog mProgressDialog;
	private String DBNAME = "dminvoicemanager.db";
	// Master Tables
	private String SERVER_DB_LIST = "serverdb";
	private String USER_SETTINGS = "usersettings";
	private String ITEM_AREA = "fArea";
	private String ITEM_COMPANY_SETTING = "fCompanySetting";
	private String ITEM_CONTROL = "fControl";
	private String ITEM_DEBTOR = "fDebtor";
	private String ITEM_LOC_DETAILS = "fItemLoc";
	private String ITEM_LOCATION = "fLocation";
	private String ITEM_PRICE = "fItemPri";
	private String ITEMS = "fItems";
	private String INV_COMPANY_BRANCH = "FCompanyBranch";
	private String INV_SAL_REP = "fSalRep";
	private String SALES_ORD_REASON = "fReason";
	private String SALES_REP_ROUTE = "fRoute";
	private String SALES_REP_ROUTEDET = "fRouteDet";
	private String BANK_DETAILS = "fBank";
	private String USER_EXPENSE = "fExpense";
	private String TOWN_DETAILS = "fTown";
	private String MERCH_DETAILS = "FMerch";
	private String YEARS_LIST = "FYearsList";
	private String MONTH_LIST = "FMonthList";
	private String SERVER_DETAILS = "serverinfo";
	private String SALES_DEALER = "fDealer";

	private String FTRGCAPUL = "FTrgCapUL";
	private String FTYPE = "fType";
	private String FSUBBRAND = "fSubBrand";
	private String FGROUP = "fGroup";
	private String FSKU = "fSku";
	private String FBRAND = "fbrand";
	// Main Invoice
	private String TEMP_REP_INVOICESUMERY = "frepInvoiceSumery";
	private String INV_DETAILS = "FinvDet";
	private String INV_HEADER = "FinvHed";

	// Stock Loading
	private String TEMP_STOCK_LOADING_SUMMARY = "frepStockLoadingSummary";
	private String STOCK_LOAD_HEAD = "fLoadhed";
	private String STOCK_LOAD_DETAIL = "fLoadDet";

	// Sales Order
	private String STOCK_ORDER_INVOICESUMERY = "fstockordInvoiceSumery";
	private String STOCK_ORDER_HEAD = "FOrdHed";
	private String STOCK_ORDER_DETAIL = "FOrddet";
	private String TEMPSTOCK_ORDER_HEAD = "TempFOrdHed";
	private String TEMPSTOCK_ORDER_DETAIL = "TempFOrddet";

	// Stock UnLoading
	private String TEMP_STOCK_LOADING_SUMMARYUN = "frepStockLoadingSummaryUn";
	private String STOCK_LOAD_HEADUN = "fUnLoadhed";
	private String STOCK_LOAD_DETAILUN = "fUnLoadDet";

	// Stock Damage
	private String TEMP_STOCK_LOADING_SUMMARYDAM = "frepStockLoadingSummaryDam";
	private String STOCK_LOAD_HEADDAM = "fDamhed";
	private String STOCK_LOAD_DETAILDAM = "fDamdet";

	// Cash /Receipt header
	private String TEMP_RECEIPT_SUMMARY = "fReceiptSummary";
	private String RECEIPT_HEADER = "fDRecHed";
	private String RECEIPT_DETAILS = "fDRecDet";

	// Adjustment
	private String TEMP_ADJUSTMENT_SUMMARY = "FAdjustmentSummary";
	private String ADJUST_ADDITION_HEADER = "FAdjHed";
	private String ADJUST_ADDITION_DETAILS = "FAdjDet";

	// Expense
	private String TEMP_DAYEXPENSE_SUMMARY = "FDayExpSummary";
	private String DAYEXPENSE_HEADER = "FDayExpHed";
	private String DAYEXPENSE_DETAILS = "FDayExpDet";

	private String RECEIPT_INVOICES = "FDDbNote";

	// None Productive Calls
	private String DAILY_NONE_PRDCALLS_HEAD = "fNonePrd";

	private SQLiteDatabase mydb;
	final private static int DIALOG_SYNC_DATA = 1;
	final private static int DIALOG_UPLOADING_DATA = 2;
	final private static int DIALOG_SYNC_SUCCESS = 3;
	final private static int DIALOG_SYNC_STOCKS = 4;
	final private static int DIALOG_DOWNLOAD_STOCKS = 5;
	final private static int DIALOG_REUPLOADING_DATA = 6;

	int checkrall = 0;
	int networkFailRec = 0;
	String ReadRefErrorUpload;

	ArrayList<String> arFinvHed = new ArrayList<String>();
	ArrayList<String> arFinvDet = new ArrayList<String>();

	ArrayList<String> arFordHed = new ArrayList<String>();
	ArrayList<String> arFordDet = new ArrayList<String>();

	ArrayList<String> arCanceleInvHedDet = new ArrayList<String>();
	ArrayList<String> arCanceleOrdHedDet = new ArrayList<String>();

	ArrayList<String> arfUnLoadhed = new ArrayList<String>();
	ArrayList<String> arfUnLoadDet = new ArrayList<String>();

	ArrayList<String> arfDRecHed = new ArrayList<String>();
	ArrayList<String> arfDRecDet = new ArrayList<String>();

	ArrayList<String> arfDamHed = new ArrayList<String>();
	ArrayList<String> arfDamDet = new ArrayList<String>();

	ArrayList<String> arFAdjHed = new ArrayList<String>();
	ArrayList<String> arFAdjDet = new ArrayList<String>();

	ArrayList<String> arNonProCallHed = new ArrayList<String>();
	ArrayList<String> arNonProCallDet = new ArrayList<String>();

	ArrayList<String> arRepGpsRecords = new ArrayList<String>();

	Cursor selectInvHeadDetailsUpdate = null,
			selectInvDetailsDataUpdate = null;
	Cursor selectInvHeadDetailsChkFail = null,
			selectInvDetailsDataChkFail = null;
	Cursor selectInvHeadDetailsReChk = null, selectInvDetailsDataReChk = null;

	int count = 0;
	int countdet = 0;
	int UploadCHK = 0; // Check fInvDet Sync Complete
	JSONArray jArray, jArrayp;
	String result = null;
	String resultp = null;
	InputStream is = null;
	InputStream isp = null;
	StringBuilder sb = null;
	StringBuilder sbp = null;
	int newinvNo;
	private int iInternalCount = 0;
	int NetFail = 0;
	private CountDownTimer mCountDown;
	String Tagid, currentUserTemp, currentUserPrefix, UserLocCode, RepInvCode,
			TransTypePrefix, AgentPrefixType, currentUserServerDB,
			serverSynchDbName, CurrentAdjLocation, AgentDealCode, serverDbName,
			connectionURL, RecordIdFI, UploadodAddDate,
			UploadAlertMessageUploading, DealerCode, gps_record_id,
			gps_device_time, gps_longitude, gps_latitude,gps_emi_number;
	AlertDialog SynchDetails = null;
	long lastId;
	String strlastId, TagId;
	int CHKSTORDTAG = 0;
	int arrayLength = 0;
	String match = "5";
	String FInvHedIndex, FInvDetIndex, FUnloadHedIndex, FReceiptHedIndex,
			FStlDamHedIndex, FStoOrdersHedIndex, FStoUnloadDetIndex,
			FReceiptDetIndex, FDamageDetIndex, FStOrderDetIndex, RepRouteCode,
			FAdjAdditionHedIndex, FAdjAdditionDetIndex, LoadingHeaderIndex,
			LoadingDetailsIndex, deviceUser;
	String SIupSummary, SOupSummary;
	int fInvHedCount = 0, fOrdHedCount = 0;
	int fInvHedCountFail = 0, fOrdHedCountFail = 0;
	/* AlertDialog UploadingDetails = null; */
	SimpleDateFormat originalFormat = new SimpleDateFormat("dd MM yyyy");
	SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
	Date date;
	private static final String TAG = null;
	// flag for Internet connection status
	Boolean isInternetPresent = false;
	// Connection detector class
	DM_ConnectionDetector cd;

	public void SyncCompleteAccept(View view) {
		SynchDetails.dismiss();
	}

	// Synch dialog box handler
	public void btnSynchCancel(View view) {
		// synchdata();
		SynchDetails.dismiss();
	}

	public void btnSynchAccept(View view) {
		// synchdata();
		SynchDetails.dismiss();

		isInternetPresent = cd.isConnectingToInternet();

		// check for Internet status
		if (isInternetPresent) {
			// Internet Connection is Present
			// make HTTP requests
			synchdata();
		} else {
			// Internet connection is not present
			// Ask user to connect to Internet
			showAlertDialog(DM_InvoiceMenu.this, "No Internet Connection",
					"You don't have internet connection.", false);
		}

	}

	public void btnSynchStocksAccept(View view) {
		// synchdata();
		SynchDetails.dismiss();

		isInternetPresent = cd.isConnectingToInternet();

		// check for Internet status
		if (isInternetPresent) {
			// Internet Connection is Present
			// make HTTP requests
			synchStocks();
		} else {
			// Internet connection is not present
			// Ask user to connect to Internet
			showAlertDialog(DM_InvoiceMenu.this, "No Internet Connection",
					"You don't have internet connection.", false);
		}

	}

	private void checkAllInvoiceUpload() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor chkUploadDet = null;
		try {
			chkUploadDet = mydb.query(INV_DETAILS, null, "invdetSync ='0'",
					null, null, null, null);
		} catch (Exception e) {
		}

		if (chkUploadDet != null) {
			if (chkUploadDet.getCount() > 0) {
				while (chkUploadDet.moveToNext()) {
					UploadCHK = 99;
					// logCurrentSynchFailDetails();

					try {
						showDialog(DIALOG_DOWNLOAD_STOCKS);
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			} else {
				UploadCHK = 0;
			}
		}
	}

	public void btnAcceptDownload(View view) {
		SynchDetails.dismiss();

		isInternetPresent = cd.isConnectingToInternet();

		// check for Internet status
		if (isInternetPresent) {
			// Internet Connection is Present
			// make HTTP requests
			synchStocks();
		} else {
			// Internet connection is not present
			// Ask user to connect to Internet
			showAlertDialog(DM_InvoiceMenu.this, "No Internet Connection",
					"You don't have internet connection.", false);
		}

	}

	public void btnCancelDownload(View view) {
		SynchDetails.dismiss();
		showmeassage();
		return;
	}

	protected void showmeassage() {
		// TODO Auto-generated method stub
		Toast.makeText(getApplicationContext(),
				"Cancel Proceeding Stock Downloading..", Toast.LENGTH_LONG)
				.show();
	}

	private void logCurrentSynchFailDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor chkUploadDetErrorLog = null;
		try {
			chkUploadDetErrorLog = mydb.query(INV_DETAILS, null,
					"invdetSync ='0'", null, null, null, null);
		} catch (Exception e) {
		}
		if (chkUploadDetErrorLog != null) {
			if (chkUploadDetErrorLog.getCount() > 0) {
				while (chkUploadDetErrorLog.moveToNext()) {
					try {

						FInvDetIndex = chkUploadDetErrorLog.getString(0);
						String RefNo = chkUploadDetErrorLog.getString(1);
						String TxnDate = chkUploadDetErrorLog.getString(2);
						String TxnType = chkUploadDetErrorLog.getString(3);
						String SeqNo = chkUploadDetErrorLog.getString(4);
						String Itemcode = chkUploadDetErrorLog.getString(5);
						String Txnseqno = chkUploadDetErrorLog.getString(6);
						String SellPrice = chkUploadDetErrorLog.getString(7);
						String BSellPrice = chkUploadDetErrorLog.getString(8);
						String TSellPrice = chkUploadDetErrorLog.getString(9);
						String BTSellPrice = chkUploadDetErrorLog.getString(10);
						String CostPrice = chkUploadDetErrorLog.getString(11);
						String CaseQty = chkUploadDetErrorLog.getString(12);
						String Type = chkUploadDetErrorLog.getString(13);
						String PiceQty = chkUploadDetErrorLog.getString(14);
						String Qty = chkUploadDetErrorLog.getString(15);
						String BalQty = chkUploadDetErrorLog.getString(16);
						String DisPer = chkUploadDetErrorLog.getString(17);
						String DisAmt = chkUploadDetErrorLog.getString(18);
						String BDisAmt = chkUploadDetErrorLog.getString(19);
						String TaxAmt = chkUploadDetErrorLog.getString(20);
						String BTaxAmt = chkUploadDetErrorLog.getString(21);
						String Amt = chkUploadDetErrorLog.getString(22);
						String BAmt = chkUploadDetErrorLog.getString(23);
						String ReaCode = chkUploadDetErrorLog.getString(24);
						String Linkrec = chkUploadDetErrorLog.getString(25);
						String RecordId = chkUploadDetErrorLog.getString(26);
						String itemDescription = chkUploadDetErrorLog
								.getString(27);
						String refInvoiceDetNo = chkUploadDetErrorLog
								.getString(28);
						String refInvoiceDetCode = chkUploadDetErrorLog
								.getString(29);
						String refInvitemCaseQty = chkUploadDetErrorLog
								.getString(30);
						String invDetAddDate = chkUploadDetErrorLog
								.getString(33);
						String itemdisper = chkUploadDetErrorLog.getString(34);
						String itemdisperval = chkUploadDetErrorLog
								.getString(35);
						String reasonCode = chkUploadDetErrorLog.getString(36);

						String[] mySettings = { RefNo, "|", TxnDate, "|",
								TxnType, "|", SeqNo, "|", Itemcode, "|",
								Txnseqno, "|", SellPrice, "|", BSellPrice, "|",
								TSellPrice, "|", BTSellPrice, "|", CostPrice,
								"|", CaseQty, "|", Type, "|", PiceQty, "|",
								Qty, "|", BalQty, "|", DisPer, "|", DisAmt,
								"|", BDisAmt, "|", TaxAmt, "|", BTaxAmt, "|",
								Amt, "|", BAmt, "|", ReaCode, "|", Linkrec,
								"|", RecordId, "|", refInvoiceDetNo, "|",
								invDetAddDate, "|", "\r\n", ";" };

						String mySettingshtml = RefNo + "|" + TxnDate + "|"
								+ TxnType + "|" + SeqNo + "|" + Itemcode + "|"
								+ Txnseqno + "|" + SellPrice + "|" + BSellPrice
								+ "|" + TSellPrice + "|" + BTSellPrice + "|"
								+ CostPrice + "|" + CaseQty + "|" + Type + "|"
								+ PiceQty + "|" + Qty + "|" + BalQty + "|"
								+ DisPer + "|" + DisAmt + "|" + BDisAmt + "|"
								+ TaxAmt + "|" + BTaxAmt + "|" + Amt + "|"
								+ BAmt + "|" + ReaCode + "|" + Linkrec + "|"
								+ RecordId + "|" + refInvoiceDetNo + "|"
								+ invDetAddDate + "|";

						String errorLogName = "ERR_LOG_"
								+ getAddDateTimeString().toString() + ".txt";

						String errorLogHtml = "ERR_LOG_"
								+ getAddDateTimeString().toString() + ".html";

						String html = "<html>"
								+ "<head>"
								+ "<title>Internal HTML File</title>"
								+ "<style type=\"text/css\">"
								+ "body {margin:2px;#61210B;font-size:small;font-weight:normal;font-family:Arial;width:300px;}"
								+ "h2{margin:5px;background-color:#184090;color:#ffffff;}"
								+ "h3{margin:5px;color:#184090}"
								+ "table{background-color:#ECEEF5;font-size:small;font-weight:normal;font-family:Arial;}"
								+ "</style>"
								+ "</head>"
								+ "<body>"
								+ "<table cellspacing=\"3\">"
								+ "<tr><td><h2>Example for Internal Memory</h2></td></tr>"
								+ "<tr><td><h3>Load HTML file from your Internal Memory</h3></td></tr>"
								+ "<tr>" + "<td>&nbsp;Internal Memory data "
								+ mySettingshtml + "</td>" + "</tr>"
								+ "</table>" + "</body></html>";

						try {
							String sfilename = errorLogHtml;
							FileOutputStream fos = this.openFileOutput(
									sfilename, Context.MODE_PRIVATE
											| Context.MODE_WORLD_READABLE);
							fos.write(html.getBytes());
							fos.flush();
							fos.close();
							/*
							 * Toast.makeText(getBaseContext(),
							 * "Write file in external memory"
							 * +sfilename+".html", Toast.LENGTH_SHORT).show();
							 */
						} catch (Exception e) {
						}

						// Create Text File
						OutputStreamWriter out = new OutputStreamWriter(
								openFileOutput(errorLogName, 0));

						for (int i = 0; i < mySettings.length; i++)
							out.write(mySettings[i]);
						out.close();

					} catch (Exception e) {

					}

				}
			}
		}
	}

	private void synchStocks() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		try {
			mydb.execSQL("DROP TABLE IF EXISTS fItemLoc");
			mydb.execSQL("create table if not exists "
					+ ITEM_LOC_DETAILS
					+ "(flocdet_id integer primary key autoincrement,LocCode text not null,ItemCode text not null,QOH text not null,RecordId text not null,timestamp_column text not null,syncRec text not null);");
		} catch (Exception e) {
		}
		mydb.close();
		new DownloadStocks().execute();

	}

	// Uploading dialog box handler
	public void btnUploadingCancel(View view) {
		// synchdata();
		SynchDetails.dismiss();
	}

	public void btnUploadingAccept(View view) {
		// synchdata();
		SynchDetails.dismiss();
		uploadingAcceptInvoiceData();
	}

	public void btnReUploadingAccept(View view) {
		// synchdata();
		SynchDetails.dismiss();
		reuploadingAcceptInvoiceData();
	}

	private void reuploadingAcceptInvoiceData() {
		// TODO Auto-generated method stub
		new ReUploadingInvoiceData().execute();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_invoice_menu);

		Bundle bundle = getIntent().getExtras();
		TagId = bundle.getString("TAGID");
		// creating connection detector class instance
		cd = new DM_ConnectionDetector(getApplicationContext());
		getConnectionUrl();
		currentuserTemp();
		salesOrderTransType();
		agentPrefixSalesOrder();
		getMachineDetails();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor chkinvoice = null;

		try {
			chkinvoice = mydb.query(INV_HEADER, null, null, null, null, null,
					null);
		} catch (Exception e) {
		}

		Button itemsList = (Button) findViewById(R.id.btnsalesHistory);
		itemsList.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_List_Items.class);
				startActivityForResult(myIntent, 0);
			}

		});

		Button addNewSalesOrder = (Button) findViewById(R.id.dmnewsalesorder);
		addNewSalesOrder.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				CheckStockLoad();
				Intent myIntent = new Intent(view.getContext(),
						DM_InvoiceSalesOrder.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				myIntent.putExtra("TAGID", "3");
				startActivityForResult(myIntent, 0);
				finish();

			}

		});

		Button addNewInvoice = (Button) findViewById(R.id.dmnewinvoice);
		addNewInvoice.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_InvoiceNew.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				myIntent.putExtra("TAGID", "3");
				startActivityForResult(myIntent, 0);
				finish();

			}

		});

		Button settings = (Button) findViewById(R.id.settings);
		settings.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_Settings.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				myIntent.putExtra("TAGID", "SALES");
				startActivityForResult(myIntent, 0);
				finish();
			}

		});

		Button logout = (Button) findViewById(R.id.departure);
		logout.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_InvoiceMainActivity.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
			}

		});
		Button DailySalesSummery = (Button) findViewById(R.id.btnsalesSummeryReports);
		DailySalesSummery.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_Reports_Generator.class);
				myIntent.putExtra("TAGID", "0/SALES");
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
			}

		});

		Button RetailerMaster = (Button) findViewById(R.id.dmretailermaster);
		RetailerMaster.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_Retailer_Master.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
			}

		});

		Button itenaryButton = (Button) findViewById(R.id.dmitenarymaster);
		itenaryButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_Itinerary_Report_Main.class);
				String passTag = "200";
				myIntent.putExtra("TAGID", passTag);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
			}
		});

		Button meterButton = (Button) findViewById(R.id.dmmeterreading);
		meterButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_Meter_Reading.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
			}
		});

		Button daySummButton = (Button) findViewById(R.id.dmdaysummary);
		daySummButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_Day_Summary.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
			}
		});

		Button SynchData = (Button) findViewById(R.id.synchdata);
		SynchData.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// get Internet status
				isInternetPresent = cd.isConnectingToInternet();

				// check for Internet status
				if (isInternetPresent) {
					// Internet Connection is Present
					// make HTTP requests
					checkCurrentSynchServerDB();
					try {
						showDialog(DIALOG_SYNC_DATA);
					} catch (Exception ex) {
						ex.printStackTrace();
					}

				} else {
					// Internet connection is not present
					// Ask user to connect to Internet
					showAlertDialog(DM_InvoiceMenu.this,
							"No Internet Connection",
							"You don't have internet connection.", false);
				}

				// synchdata();

			}

			private void checkCurrentSynchServerDB() {
				// TODO Auto-generated method stub
				SQLiteDatabase mydb;
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				Cursor selectServerDB = null;
				try {
					selectServerDB = mydb.query(USER_SETTINGS, null, null,
							null, null, null, null);
				} catch (Exception e) {
				}
				if (selectServerDB != null) {
					if (selectServerDB.getCount() > 0) {
						while (selectServerDB.moveToNext()) {
							serverSynchDbName = selectServerDB.getString(7);
						}
					}
				}
				selectServerDB.close();
				mydb.close();

			}

		});

		Button synchstocks = (Button) findViewById(R.id.synchstocks);
		synchstocks.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				checkAllInvoiceUpload();

				if (UploadCHK == 0) {

					// get Internet status
					isInternetPresent = cd.isConnectingToInternet();

					// check for Internet status
					if (isInternetPresent) {
						// Internet Connection is Present
						// make HTTP requests
						checkCurrentSynchServerDB();
						try {
							showDialog(DIALOG_SYNC_STOCKS);
						} catch (Exception ex) {
							ex.printStackTrace();
						}

					} else {
						// Internet connection is not present
						// Ask user to connect to Internet
						showAlertDialog(DM_InvoiceMenu.this,
								"No Internet Connection",
								"You don't have internet connection.", false);
					}

					// synchdata();
				}
			}

			private void checkCurrentSynchServerDB() {
				// TODO Auto-generated method stub
				SQLiteDatabase mydb;
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				Cursor selectServerDB = null;
				try {
					selectServerDB = mydb.query(USER_SETTINGS, null, null,
							null, null, null, null);
				} catch (Exception e) {
				}
				if (selectServerDB != null) {
					if (selectServerDB.getCount() > 0) {
						while (selectServerDB.moveToNext()) {
							serverSynchDbName = selectServerDB.getString(7);
						}
					}
				}
				selectServerDB.close();
				mydb.close();

			}

		});

		Button uploadingData = (Button) findViewById(R.id.uploadingData);
		uploadingData.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// get Internet status
				isInternetPresent = cd.isConnectingToInternet();
				// check for Internet status
				if (isInternetPresent) {
					// Internet Connection is Present
					// make HTTP requests
					checkCurrentServerDB();
					try {
						showDialog(DIALOG_UPLOADING_DATA);
					} catch (Exception ex) {
						ex.printStackTrace();
					}
					// uploadingInvoiceData();
				} else {
					// Internet connection is not present
					// Ask user to connect to Internet
					showAlertDialog(DM_InvoiceMenu.this,
							"No Internet Connection",
							"You don't have internet connection.", false);
				}

			}

			private void checkCurrentServerDB() {
				// TODO Auto-generated method stub
				SQLiteDatabase mydb;
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				Cursor selectServerDB = null;
				try {
					selectServerDB = mydb.query(USER_SETTINGS, null, null,
							null, null, null, null);
				} catch (Exception e) {
				}
				if (selectServerDB != null) {
					if (selectServerDB.getCount() > 0) {
						while (selectServerDB.moveToNext()) {
							currentUserServerDB = selectServerDB.getString(7);
						}
					}
				}
				selectServerDB.close();
				mydb.close();
			}

		});
		// Uploading Data using Old WebService
		Button reUploadingData = (Button) findViewById(R.id.reUploadingData);
		reUploadingData.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// get Internet status
				isInternetPresent = cd.isConnectingToInternet();
				// check for Internet status
				if (isInternetPresent) {
					// Internet Connection is Present
					// make HTTP requests
					checkCurrentServerDB();
					try {
						showDialog(DIALOG_REUPLOADING_DATA);
					} catch (Exception ex) {
						ex.printStackTrace();
					}
					// uploadingInvoiceData();
				} else {
					// Internet connection is not present
					// Ask user to connect to Internet
					showAlertDialog(DM_InvoiceMenu.this,
							"No Internet Connection",
							"You don't have internet connection.", false);
				}

			}

			private void checkCurrentServerDB() {
				// TODO Auto-generated method stub
				SQLiteDatabase mydb;
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				Cursor selectServerDB = null;
				try {
					selectServerDB = mydb.query(USER_SETTINGS, null, null,
							null, null, null, null);
				} catch (Exception e) {
				}
				if (selectServerDB != null) {
					if (selectServerDB.getCount() > 0) {
						while (selectServerDB.moveToNext()) {
							currentUserServerDB = selectServerDB.getString(7);
						}
					}
				}
				selectServerDB.close();
				mydb.close();
			}

		});

		Button StockLoadingData = (Button) findViewById(R.id.stockloading);
		StockLoadingData.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_Stock_Loading.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
			}

		});

		Button StockunLoadingData = (Button) findViewById(R.id.stockunloading);
		StockunLoadingData.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_Stock_UnLoading.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
			}

		});

		Button StockdmLoadingData = (Button) findViewById(R.id.damageloading);
		StockdmLoadingData.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_Damage_Loading.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
			}

		});

		Button DMCashChequeReceipt = (Button) findViewById(R.id.dmnewcashchequereceipt);
		DMCashChequeReceipt.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_Cash_Cheque_Receipt.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				myIntent.putExtra("TAGID", "3");
				startActivityForResult(myIntent, 0);
				finish();
			}

		});

		Button DMExpenseReimbursement = (Button) findViewById(R.id.dmexpensereimbursement);
		DMExpenseReimbursement.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_Expense_Reimbursement.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				myIntent.putExtra("TAGID", "3");
				startActivityForResult(myIntent, 0);
				finish();
			}

		});

		Button DMProductiveCalls = (Button) findViewById(R.id.dmproductivecalls);
		DMProductiveCalls.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_ProductiveCalls.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				myIntent.putExtra("TAGID", "3");
				startActivityForResult(myIntent, 0);
				finish();
			}

		});

		Button DMAdjustmentAdition = (Button) findViewById(R.id.dmadjustmentAdition);
		DMAdjustmentAdition.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_AdjustmentAdition.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				myIntent.putExtra("TAGID", "3");
				startActivityForResult(myIntent, 0);
				finish();
			}

		});

		Button DMAdjustmentDeduction = (Button) findViewById(R.id.dmadjustmentDeduction);
		DMAdjustmentDeduction.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_AdjustmentDeduction.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				myIntent.putExtra("TAGID", "3");
				startActivityForResult(myIntent, 0);
				finish();
			}

		});

		Button DMItemsMaster = (Button) findViewById(R.id.dmitemsmaster);
		DMItemsMaster.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_Item_Master.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
			}

		});

		Button DMProductiveCallsSO = (Button) findViewById(R.id.dmproductivecallsSO1);
		DMProductiveCallsSO.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_ProductiveCallsOfSO.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				myIntent.putExtra("TAGID", "3");
				startActivityForResult(myIntent, 0);
				finish();
			}

		});

	}

	private void getMachineDetails() {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		String Model = android.os.Build.MODEL;
		String id = android.os.Build.ID;
		deviceUser = Model + "_" + id;
	}

	// Display Network connection Fail Alert
	public void showAlertDialog(Context context, String title, String message,
			Boolean status) {
		final AlertDialog alertDialog = new AlertDialog.Builder(context)
				.create();

		// Setting Dialog Title
		alertDialog.setTitle(title);

		// Setting Dialog Message
		alertDialog.setMessage(message);

		// Setting alert dialog icon
		alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// new DownloadAdministrative().execute();
				alertDialog.dismiss();
			}
		});

		// Showing Alert Message
		alertDialog.show();
	}

	// Display Network connection Fail Alert
	public void showAlertDialogUpload(Context context, String title,
			String message, Boolean status) {
		AlertDialog alertDialog = new AlertDialog.Builder(context).create();

		// Setting Dialog Title
		alertDialog.setTitle(title);

		// Setting Dialog Message
		alertDialog.setMessage(message);

		// Setting alert dialog icon
		alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				new UploadingInvoiceDataValues().execute();
			}
		});

		// Showing Alert Message
		alertDialog.show();
	}

	// Retrieve Current URL
	private void getConnectionUrl() {
		// TODO Auto-generated method stub
		Cursor getserverurl = null;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			getserverurl = mydb.query(SERVER_DETAILS, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}
		if (getserverurl != null) {
			if (getserverurl.getCount() > 0) {
				while (getserverurl.moveToNext()) {
					connectionURL = getserverurl.getString(1);
					Log.v(TAG, "connectionURL:" + connectionURL);
				}
			}
		}
		mydb.close();
	}

	private void currentuserTemp() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectCurrentuserrec = null;
		try {
			selectCurrentuserrec = mydb.query(USER_SETTINGS, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentuserrec != null) {
			if (selectCurrentuserrec.getCount() > 0) {
				while (selectCurrentuserrec.moveToNext()) {
					currentUserTemp = selectCurrentuserrec.getString(1);
					currentUserPrefix = selectCurrentuserrec.getString(2);
					UserLocCode = selectCurrentuserrec.getString(5);
					serverDbName = selectCurrentuserrec.getString(7);
					RepRouteCode = selectCurrentuserrec.getString(11);
				}
			}
		}

		selectCurrentuserrec.close();
		mydb.close();
	}

	protected void CheckStockLoad() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb = openOrCreateDatabase(DBNAME,
				Context.MODE_PRIVATE, null);
		Cursor CheckStockLoadcur = null;

		try {
			CheckStockLoadcur = mydb.query(STOCK_ORDER_INVOICESUMERY, null,
					"repusername='" + currentUserTemp + "'", null, null, null,
					null);

			// AND invlateststate ='9'"
		} catch (Exception e1) {
		}
		try {
			if (CheckStockLoadcur != null) {
				if (CheckStockLoadcur.getCount() > 0) {
					while (CheckStockLoadcur.moveToNext()) {
						String checkState = CheckStockLoadcur.getString(16);
						if (checkState.equals("9")) {

						} else {
							// CheckLastStockLoadAvailable();
						}

					}
				} else {
					SaveNewStockLoadRecord();
				}
			}

		} catch (Exception e1) {
		}
	}

	private void CheckLastStockLoadAvailable() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb = openOrCreateDatabase(DBNAME,
				Context.MODE_PRIVATE, null);
		Cursor chkItemSequence = null;

		String query = "SELECT * from frepStockLoadingSummary order by RepCode DESC limit 1";
		Cursor c = mydb.rawQuery(query, null);
		if (c != null && c.moveToLast()) {
			String RefNo = c.getString(16);
			String RepCode = c.getString(18);
			if (RepCode.equals(currentUserTemp)) {
				lastId = c.getLong(0);
				strlastId = Long.toString(lastId);
				CHKSTORDTAG = 12;
				SaveNewStockLoadRecord();
			}
		}
	}

	private void SaveNewStockLoadRecord() {
		// TODO Auto-generated method stub
		RepInvCode = TransTypePrefix.trim() + AgentPrefixType.trim()
				+ currentUserPrefix;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		try {
			ContentValues saveTempuserinvoice = new ContentValues();
			saveTempuserinvoice.put("repusername", currentUserTemp);
			saveTempuserinvoice.put("repprefix", currentUserPrefix);
			saveTempuserinvoice.put("tempRepInvNoCode", RepInvCode);
			if (CHKSTORDTAG == 0) {
				saveTempuserinvoice.put("tempRepInvSerial", "1");
			} else if (CHKSTORDTAG == 12) {
				saveTempuserinvoice.put("tempRepInvSerial", strlastId);
			}
			saveTempuserinvoice.put("invoiceComplete", "0");
			saveTempuserinvoice.put("activeInvoice", "1");
			saveTempuserinvoice.put("activeInvoiceValue", "0");
			saveTempuserinvoice.put("activeInvItemDiscount", "0");
			saveTempuserinvoice.put("activeInvCusDiscount", "0");
			saveTempuserinvoice.put("activeInvCusDiscountValue", "0");
			saveTempuserinvoice.put("InvoiceCustomerCode", "0");
			saveTempuserinvoice.put("InvoiceCustomerName", "");
			saveTempuserinvoice.put("InvoiceSynchState", "0");
			saveTempuserinvoice.put("recordDate", getCurrentTimeString());
			saveTempuserinvoice.put("recordSynchDate", "0");
			saveTempuserinvoice.put("invlateststate", "9");
			saveTempuserinvoice.put("activeInvoiceReturnValue", "0");
			saveTempuserinvoice.put("activeInvoiceRemarks", "");
			saveTempuserinvoice.put("invoiceNoOfItems", "0");
			saveTempuserinvoice.put("invoiceRef", "0");
			saveTempuserinvoice.put("invoiceRefStl", "");
			saveTempuserinvoice.put("invoiceRefStl", "");
			saveTempuserinvoice.put("invoicedelidate", "");
			saveTempuserinvoice.put("invManuRefNo", "");
			mydb.insert(STOCK_ORDER_INVOICESUMERY, null, saveTempuserinvoice);
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured..",
					Toast.LENGTH_SHORT).show();
		}

		mydb.close();
	}

	protected void salesOrderTransType() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectTransType = null;

		try {
			selectTransType = mydb.query(ITEM_COMPANY_SETTING, null, null,
					null, null, null, null);
		} catch (Exception e) {
		}
		if (selectTransType != null) {
			if (selectTransType.getCount() > 0) {
				while (selectTransType.moveToNext()) {
					String cSettingsCode = selectTransType.getString(1);
					String cCharValue = selectTransType.getString(4);
					if (cSettingsCode.equals("SECORD")) {
						TransTypePrefix = cCharValue.trim();
					}

				}
			}
		}
		selectTransType.close();
		mydb.close();
	}

	protected void agentPrefixSalesOrder() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectAgentPreType = null;

		try {
			selectAgentPreType = mydb.query(ITEM_CONTROL, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectAgentPreType != null) {
			if (selectAgentPreType.getCount() > 0) {
				while (selectAgentPreType.moveToNext()) {
					AgentPrefixType = selectAgentPreType.getString(18);
					AgentDealCode = selectAgentPreType.getString(19);
				}

			}
		}
		selectAgentPreType.close();
		mydb.close();
	}

	protected void uploadingAcceptInvoiceData() {
		// TODO Auto-generated method stub
		// new UploadingInvoiceData().execute();
		new UploadingInvoiceDataValues().execute();

	}

	// ******Uploading Details Using New Rallback Web Service******
	private class UploadingInvoiceDataValues extends
			AsyncTask<Void, Void, Void> {
		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(DM_InvoiceMenu.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Uploading");
			// Set progressdialog message
			mProgressDialog.setMessage("Uploading Invoice Details...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			Cursor selectFcompanyBranch = null;
			// Secondry Invoice Cursors
			Cursor selectInvHeadDetails = null;
			Cursor selectInvDetailsData = null;
			// Sales Order Invoice Cursors
			Cursor selectOrderHeader = null;
			Cursor selectOrderDetails = null;
			// Secondry invoice Cancel Details
			Cursor selectSIcancelHedDetDetails = null;
			Cursor selectSOcancelHedDetDetails = null;

			// Unloading Records Details
			Cursor selectStockUnloadHeader = null;
			Cursor selectStockUnLoadDetails = null;

			// Receipt Records Details
			Cursor selectReceiptHeadDetails = null;
			Cursor selectInvReceiptDetails = null;

			// Damage Records Details
			Cursor selectStockfDamhed = null;
			Cursor selectStockfDamDet = null;

			// Adjustment Records Details
			Cursor selectAdjustmentHeader = null;
			Cursor selectAdjustmentDetails = null;

			// Select Non Productive Call
			Cursor selectNonProCallDetails = null;

			// Select Dealer4
			Cursor selectDealer = null;

			Cursor salesRegGps = null;
			try {
				String query = "SELECT _id,device_time,longitude,latitude FROM fRepGps Where sync_state = '0'";
				salesRegGps = mydb.rawQuery(query, null);
			} catch (Exception e) {
			}

			try {
				selectDealer = mydb.query(SALES_DEALER, null, null, null, null,
						null, null);
			} catch (Exception e) {

			}

			// company branch
			try {
				selectFcompanyBranch = mydb.query(INV_COMPANY_BRANCH, null,
						"BranchCode ='" + currentUserTemp + "'", null, null,
						null, null);
			} catch (Exception e) {
			}

			// Canceled Secondry Invoice Uploading
			try {
				String queryCancelSI = "SELECT FH.RefNo,FH.RefNo1,FH.InvType,FH.TxnDate,FH.ManuRef,FH.DealCode,FH.RepCode,FH.AreaCode,FH.RouteCode,FH.DebCode,FH.LocCode,FH.Remarks,FH.CostCode,FH.CurCode,FH.CurRate,FH.TxnType,FH.InvAmt,FH.OutDis,FH.InvDis,FH.TotMkrAmt,FH.UnOvAmt,FH.TotalDis,FH.TotalAmt,FH.AddUser,FH.AddDateInvHead,FH.AddMach,FH.prtcopy,FD.RefNo,FD.SeqNo,FD.Itemcode,FD.Txnseqno,FD.SellPrice,FD.BSellPrice,FD.TSellPrice,FD.BTSellPrice,FD.CostPrice,FD.CaseQty,FD.PiceQty,FD.Type,FD.Qty,FD.BalQty,FD.DisPer,FD.DisAmt,FD.BDisAmt,FD.itemdisper,FD.itemdisperval,FD.TaxAmt,FD.BTaxAmt,FD.Amt,FD.Bamt,FD.ReaCode,FD.Linkrec,FSUM.invoiceComplete,FSUM.invoiceRef FROM Finvhed FH,FinvDet FD,frepInvoiceSumery FSUM Where FH.RefNo = FD.RefNo AND FH.RefNo = FSUM.invoiceRef AND FSUM.invoiceComplete = '5'";
				selectSIcancelHedDetDetails = mydb
						.rawQuery(queryCancelSI, null);
			} catch (Exception e) {
			}
			// Canceled Sales Order Invoice Uploading
			try {
				String queryCancelSO = "SELECT OH.RefNo,OH.TxnDate,OH.ManuRef,OH.DelvDate,OH.DealCode,OH.RepCode,OH.AreaCode,OH.RouteCode,OH.DebCode,OH.LocCode,OH.Remarks,OH.CostCode,OH.CurCode,OH.CurRate,OH.TxnType,OH.InvAmt,OH.OutDis,OH.InvDis,OH.TotMkrAmt,OH.UnOvAmt,OH.TotalDis,OH.TotalAmt,OH.InvFlg,OD.SeqNo,OD.Itemcode,OD.Txnseqno,OD.SellPrice,OD.BSellPrice,OD.TSellPrice,OD.BTSellPrice,OD.CostPrice,OD.CaseQty,OD.PiceQty,OD.Type,OD.Qty,OD.BalQty,OD.DisPer,OD.DisAmt,OD.BDisAmt,OD.TaxAmt,OD.BTaxAmt,OD.Amt,OD.Bamt,OD.ReaCode,OH.AddUser,OH.ohAddDate,OH.AddMach,OH.prtcopy,OD.itemdisper,OD.itemdisperval,OSUM.invoiceComplete,OSUM.invoiceRef,OD.RefNo,OH.AddMach FROM FOrdHed OH,FOrddet OD,fstockordInvoiceSumery OSUM Where OH.RefNo = OD.RefNo AND OH.RefNo = OSUM.invoiceRef AND OSUM.invoiceComplete = '5'";
				selectSOcancelHedDetDetails = mydb
						.rawQuery(queryCancelSO, null);
			} catch (Exception e) {
			}

			// Stocks Unloading Header Uploading
			// Unloading header
			try {
				selectStockUnloadHeader = mydb.query(STOCK_LOAD_HEADUN, null,
						"stlhedunSync = '0'", null, null, null, null);
			} catch (Exception e) {
			}

			try {
				selectStockUnLoadDetails = mydb.query(STOCK_LOAD_DETAILUN,
						null, "stldetunSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}

			// Receipt Uploading
			try {
				selectReceiptHeadDetails = mydb.query(RECEIPT_HEADER, null,
						"recipthedSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}
			try {
				selectInvReceiptDetails = mydb.query(RECEIPT_DETAILS, null,
						"reciptdetSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}

			// Damage Transfer
			try {
				selectStockfDamhed = mydb.query(STOCK_LOAD_HEADDAM, null,
						"stldmhedSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}

			try {
				selectStockfDamDet = mydb.query(STOCK_LOAD_DETAILDAM, null,
						"stldmdetSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}
			// Stock adjustment , deduction header
			try {
				selectAdjustmentHeader = mydb.query(ADJUST_ADDITION_HEADER,
						null, "adjHedSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}

			try {
				selectAdjustmentDetails = mydb.query(ADJUST_ADDITION_DETAILS,
						null, "adjDetSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}

			// Get Non productive Call
			try {
				selectNonProCallDetails = mydb.query(DAILY_NONE_PRDCALLS_HEAD,
						null, "Status = 'NP' AND stldmhedSync = '0'", null,
						null, null, null);
			} catch (Exception e) {
			}

			if (selectDealer != null) {
				if (selectDealer.getCount() > 0) {
					while (selectDealer.moveToNext()) {
						DealerCode = selectDealer.getString(1);
					}
				}
			}

			// ******Upload fCompanyBranch**************
			checkNetworkUploading();
			if (selectFcompanyBranch != null) {
				if (selectFcompanyBranch.getCount() > 0) {
					while (selectFcompanyBranch.moveToNext()) {
						String BranchCode = selectFcompanyBranch.getString(1);
						String RecordId = selectFcompanyBranch.getString(2);
						String cSettingsCode = selectFcompanyBranch
								.getString(3);

						if (cSettingsCode.equals("SECINV")
								|| cSettingsCode.equals("SECORD")) {

							String nNumVal = selectFcompanyBranch.getString(4);
							HttpPost request = new HttpPost(
									connectionURL
											+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/InUpdatefCompanyBranch");

							JSONStringer userJson = null;

							try {

								userJson = new JSONStringer().object()
										.key("fCBInUp").object()
										.key("BranchCode").value(BranchCode)
										.key("cSettingsCode")
										.value(cSettingsCode).key("nNumVal")
										.value(nNumVal).key("DbName")
										.value(currentUserServerDB).endObject();
								// .key("RecordId").value("10")
								Log.e("json", "json created");
							} catch (JSONException e) {

								// TODO Auto-generated catch block
								e.printStackTrace();
							}

							StringEntity entity = null;
							try {
								entity = new StringEntity(userJson.toString(),
										"UTF-8");
							} catch (UnsupportedEncodingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							entity.setContentEncoding(new BasicHeader(
									HTTP.CONTENT_TYPE, "application/json"));
							entity.setContentType("application/json");

							request.setEntity(entity);
							Log.e("Request xxx", "Request xxx:" + userJson);
							// Send request to WCF service
							DefaultHttpClient httpClient = new DefaultHttpClient();

							try {
								Log.e("response", "connect");
								HttpResponse response = httpClient
										.execute(request);
								// ===========================================================
								HttpEntity entitye = response.getEntity();
								is = entity.getContent();
								if (is != null) {

									try {
										BufferedReader reader = new BufferedReader(
												new InputStreamReader(is,
														"iso-8859-1"), 8);
										sb = new StringBuilder();
										sb.append(reader.readLine() + "\n");
										String line = "0";
										while ((line = reader.readLine()) != null) {
											sb.append(line + "\n");
										}
										is.close();
										String result = sb.toString();
										Log.e("String Responce",
												"Print Responce xxx:" + result);
									} catch (Exception e1) {
										e1.printStackTrace();
									}
								}
								// ==================================
								Log.e("response",
										"response get:" + response.toString());
								// System.out.println(response.toString());
								BufferedReader reader = new BufferedReader(
										new InputStreamReader(response
												.getEntity().getContent(),
												"UTF-8"));
								String json = reader.readLine();
								Log.e("json string", "test " + json.toString()
										+ " lazım");
								System.out.println(json);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}

					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}

			}

			// *******Secondry Invoice Uploading Start********
			// ******Upload FInvHed**************
			checkNetworkUploading();
			// int fInvHedCount = 0 , fOrdHedCount = 0;

			Cursor getRecordFInvHed = null;
			// *******Secondry Invoice********
			try {
				getRecordFInvHed = mydb.query(INV_HEADER, null,
						"invhedSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}

			if (getRecordFInvHed != null) {
				if (getRecordFInvHed.getCount() > 0) {
					while (getRecordFInvHed.moveToNext()) {
						fInvHedCount = getRecordFInvHed.getCount();

						String RefNoFHedUploading = getRecordFInvHed
								.getString(1);
						Log.v(TAG, "Array fInvHed XXXXX:" + RefNoFHedUploading);

						try {
							selectInvHeadDetails = mydb.query(INV_HEADER, null,
									"RefNo ='" + RefNoFHedUploading + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						try {
							selectInvDetailsData = mydb.query(INV_DETAILS,
									null,
									"RefNo ='" + RefNoFHedUploading + "'",
									null, null, null, null);
						} catch (Exception e) {
						}

						if (selectInvHeadDetails != null) {
							if (selectInvHeadDetails.getCount() > 0) {
								while (selectInvHeadDetails.moveToNext()) {
									String RefNo = selectInvHeadDetails
											.getString(1);
									String RefNo1 = selectInvHeadDetails
											.getString(2);
									String InvType = selectInvHeadDetails
											.getString(3);
									String TxnDate = selectInvHeadDetails
											.getString(4);
									try {
										date = originalFormat.parse(TxnDate
												.replaceAll("[-+/.^:,]", " "));
										TxnDate = targetFormat.format(date);
									} catch (ParseException ex) {
										TxnDate = "1900-01-01";
									}
									String ManuRef = selectInvHeadDetails
											.getString(5);
									String DealCode = selectInvHeadDetails
											.getString(6);
									String RepCode = selectInvHeadDetails
											.getString(7);
									String AreaCode = selectInvHeadDetails
											.getString(8);
									String RouteCode = selectInvHeadDetails
											.getString(9);
									String DebCode = selectInvHeadDetails
											.getString(10);
									String LocCode = selectInvHeadDetails
											.getString(11);
									String Remarks = selectInvHeadDetails
											.getString(12);
									String CostCode = selectInvHeadDetails
											.getString(13);
									String CurCode = selectInvHeadDetails
											.getString(14);
									String CurRate = selectInvHeadDetails
											.getString(15);
									String TxnType = selectInvHeadDetails
											.getString(16);
									String InvAmt = selectInvHeadDetails
											.getString(17);
									String OutDis = selectInvHeadDetails
											.getString(18);

									String AddUser = selectInvHeadDetails
											.getString(24);
									String AddDate = selectInvHeadDetails
											.getString(25);
									String AddMach = selectInvHeadDetails
											.getString(26);
									String prtcopy = selectInvHeadDetails
											.getString(27);
									String TranBatch = selectInvHeadDetails
											.getString(30);
									String InvDis = "0", UnOvAmts = "0", TotMkrAmt = "0", TotalDis = "0", TotalAmt = "0", PrintFTotalAmt = "0", outDisVal = "0", LineItemsDisString = "0";
									try {
										// Invoice Discount Value
										InvDis = selectInvHeadDetails
												.getString(19);
										double InvDisVal = Double
												.parseDouble(InvDis.replaceAll(
														"[,]", ""));
										TotMkrAmt = selectInvHeadDetails
												.getString(20);
										UnOvAmts = selectInvHeadDetails
												.getString(21);
										// Total Discount
										TotalDis = selectInvHeadDetails
												.getString(22);
										double TotalDisVal = Double
												.parseDouble(TotalDis
														.replaceAll("[,]", ""));
										TotalAmt = selectInvHeadDetails
												.getString(23);
										double TotalAmtdou = Double
												.parseDouble(TotalAmt
														.replaceAll("[,]", ""));
										double FTotalAmt = TotalAmtdou + 0.00;
										PrintFTotalAmt = Double
												.toString(FTotalAmt);

										// Header Discount
										outDisVal = selectInvHeadDetails
												.getString(33);
										double outDisValue = Double
												.parseDouble(outDisVal
														.replaceAll("[,]", ""));
										// Line Items Discount
										double LineItemsDis = TotalDisVal
												- (InvDisVal + outDisValue);
										LineItemsDisString = Double
												.toString(LineItemsDis);
									} catch (Exception e) {

									}

									// Create values JSONArray
									JSONArray valuesarrayFinvHed = new JSONArray();

									try {
										// Create values jsonObject
										JSONObject valuesJsonFinvHed = new JSONObject();
										valuesJsonFinvHed.put("RefNo", RefNo);
										valuesJsonFinvHed.put("RefNo1", RefNo1);
										valuesJsonFinvHed.put("InvType",
												InvType);
										valuesJsonFinvHed.put("TxnDate",
												TxnDate);
										valuesJsonFinvHed.put("ManuRef",
												ManuRef);
										valuesJsonFinvHed.put("DealCode",
												DealCode);
										valuesJsonFinvHed.put("RepCode",
												RepCode);
										valuesJsonFinvHed.put("AreaCode",
												AreaCode);
										valuesJsonFinvHed.put("RouteCode",
												RouteCode);
										valuesJsonFinvHed.put("DebCode",
												DebCode);
										valuesJsonFinvHed.put("LocCode",
												LocCode);
										valuesJsonFinvHed.put("Remarks",
												Remarks);
										valuesJsonFinvHed.put("CostCode",
												CostCode);
										valuesJsonFinvHed.put("CurCode",
												CurCode);
										valuesJsonFinvHed.put("CurRate",
												CurRate);
										valuesJsonFinvHed.put("TxnType",
												TxnType);
										valuesJsonFinvHed.put("InvAmt", InvAmt);
										valuesJsonFinvHed.put("OutDis", OutDis);
										valuesJsonFinvHed.put("InvDis", InvDis);
										valuesJsonFinvHed
												.put("TotMkrAmt", TotMkrAmt
														.replaceAll("[,]", ""));
										valuesJsonFinvHed.put("UnOvAmt",
												UnOvAmts.replaceAll("[,]", ""));
										valuesJsonFinvHed.put("TotalDis",
												TotalDis.replaceAll("[,]", ""));
										valuesJsonFinvHed.put("TotalItmDis",
												LineItemsDisString.replaceAll(
														"[,]", ""));
										valuesJsonFinvHed.put("TotalAmt",
												PrintFTotalAmt.replaceAll(
														"[,]", ""));
										valuesJsonFinvHed.put("AddUser",
												AddUser);
										valuesJsonFinvHed.put("AddDate",
												AddDate);
										valuesJsonFinvHed.put("AddMach",
												AddMach);
										valuesJsonFinvHed.put("prtcopy",
												prtcopy);
										valuesJsonFinvHed.put("outDisVal",
												outDisVal);
										valuesJsonFinvHed.put("TranBatch", " ");
										valuesJsonFinvHed.put("DbName",
												currentUserServerDB);

										valuesarrayFinvHed
												.put(valuesJsonFinvHed
														.remove("[,]"));
										arFinvHed.add(valuesJsonFinvHed
												.toString());
									} catch (Exception ex) {
										ex.printStackTrace();
									}
								}
								/*
								 * arrayLength = 7; progressHandler
								 * .sendMessage(
								 * progressHandler.obtainMessage());
								 */
							}
						}
						checkNetworkUploading();
						if (selectInvDetailsData != null) {
							if (selectInvDetailsData.getCount() > 0) {
								while (selectInvDetailsData.moveToNext()) {
									String RefNo = selectInvDetailsData
											.getString(1);
									String TxnDate = selectInvDetailsData
											.getString(2);
									try {
										date = originalFormat.parse(TxnDate
												.replaceAll("[-+/.^:,]", " "));
										TxnDate = targetFormat.format(date);

									} catch (ParseException ex) {
										TxnDate = "1900-01-01";
									}
									String TxnType = selectInvDetailsData
											.getString(3);
									String SeqNo = selectInvDetailsData
											.getString(4);
									String Itemcode = selectInvDetailsData
											.getString(5);
									String Txnseqno = selectInvDetailsData
											.getString(6);
									String SellPrice = selectInvDetailsData
											.getString(7);
									String BSellPrice = selectInvDetailsData
											.getString(8);
									String TSellPrice = selectInvDetailsData
											.getString(9);
									String BTSellPrice = selectInvDetailsData
											.getString(10);
									String CostPrice = selectInvDetailsData
											.getString(11);
									String CaseQty = selectInvDetailsData
											.getString(12);
									String Type = selectInvDetailsData
											.getString(13);
									String PiceQty = selectInvDetailsData
											.getString(14);
									String Qty = selectInvDetailsData
											.getString(15);
									String BalQty = selectInvDetailsData
											.getString(16);
									String DisPer = selectInvDetailsData
											.getString(17);
									String DisAmt = selectInvDetailsData
											.getString(18);
									String BDisAmt = selectInvDetailsData
											.getString(19);
									String TaxAmt = selectInvDetailsData
											.getString(20);
									String BTaxAmt = selectInvDetailsData
											.getString(21);
									String Amt = selectInvDetailsData
											.getString(22);
									String BAmt = selectInvDetailsData
											.getString(23);
									String ReaCode = selectInvDetailsData
											.getString(24);
									String Linkrec = selectInvDetailsData
											.getString(25);
									String RecordId = selectInvDetailsData
											.getString(26);
									String itemDescription = selectInvDetailsData
											.getString(27);
									String refInvoiceDetNo = selectInvDetailsData
											.getString(28);
									String refInvoiceDetCode = selectInvDetailsData
											.getString(29);
									String refInvitemCaseQty = selectInvDetailsData
											.getString(30);
									String invDetAddDate = selectInvDetailsData
											.getString(33);
									String itemdisper = selectInvDetailsData
											.getString(34);
									String itemdisperval = selectInvDetailsData
											.getString(35);
									String DisValueAmtCalStr = "0";
									try {
										double totlineItemDis = Double
												.parseDouble(BDisAmt
														.replaceAll("[,]", ""));
										double DisPerAmount = Double
												.parseDouble(itemdisperval
														.replaceAll("[,]", ""));
										double DisValueAmtCal = totlineItemDis
												- DisPerAmount;
										DisValueAmtCalStr = Double
												.toString(DisValueAmtCal);
									} catch (Exception e) {

									}

									String reasonCode = selectInvDetailsData
											.getString(36);

									// Create values JSONArray
									JSONArray valuesarrayFinvDet = new JSONArray();

									try {
										checkrall = checkrall + 1;
										// Create values jsonObject
										JSONObject valuesJsonFinvDet = new JSONObject();
										valuesJsonFinvDet.put("RefNo",
												refInvoiceDetCode);
										valuesJsonFinvDet.put("TxnDate",
												TxnDate);
										valuesJsonFinvDet.put("TxnType",
												TxnType);
										valuesJsonFinvDet.put("SeqNo", SeqNo);
										valuesJsonFinvDet.put("Itemcode",
												Itemcode);
										valuesJsonFinvDet.put("Txnseqno",
												Txnseqno);
										valuesJsonFinvDet
												.put("SellPrice", SellPrice
														.replaceAll("[,]", ""));
										valuesJsonFinvDet
												.put("SellPrice", SellPrice
														.replaceAll("[,]", ""));
										valuesJsonFinvDet.put("BSellPrice",
												BSellPrice
														.replaceAll("[,]", ""));
										valuesJsonFinvDet.put("TSellPrice",
												TSellPrice
														.replaceAll("[,]", ""));
										valuesJsonFinvDet.put("BTSellPrice",
												BTSellPrice.replaceAll("[,]",
														""));
										valuesJsonFinvDet
												.put("CostPrice", CostPrice
														.replaceAll("[,]", ""));
										valuesJsonFinvDet.put("CaseQty",
												CaseQty.replaceAll("[,]", ""));
										valuesJsonFinvDet.put("PiceQty",
												PiceQty.replaceAll("[,]", ""));
										valuesJsonFinvDet.put("Type", Type);
										valuesJsonFinvDet.put("Qty",
												Qty.replaceAll("[,]", ""));
										valuesJsonFinvDet.put("BalQty",
												BalQty.replaceAll("[,]", ""));
										valuesJsonFinvDet.put("DisPer",
												DisPer.replaceAll("[,]", ""));
										valuesJsonFinvDet.put("DisAmt",
												DisAmt.replaceAll("[,]", ""));
										valuesJsonFinvDet.put("BDisAmt",
												BDisAmt.replaceAll("[,]", ""));
										valuesJsonFinvDet.put("TaxAmt",
												TaxAmt.replaceAll("[,]", ""));
										valuesJsonFinvDet.put("BTaxAmt",
												BTaxAmt.replaceAll("[,]", ""));
										valuesJsonFinvDet.put("Amt",
												Amt.replaceAll("[,]", ""));
										valuesJsonFinvDet.put("BAmt",
												BAmt.replaceAll("[,]", ""));
										valuesJsonFinvDet.put("ReaCode",
												ReaCode);
										valuesJsonFinvDet.put("Linkrec", "0");
										valuesJsonFinvDet.put("DisPerAmt",
												itemdisperval.replaceAll("[,]",
														""));
										valuesJsonFinvDet.put("DisValAmt",
												DisValueAmtCalStr.replaceAll(
														"[,]", ""));
										valuesJsonFinvDet.put("LocCode",
												UserLocCode);
										valuesJsonFinvDet.put("DbName",
												currentUserServerDB);
										valuesarrayFinvDet
												.put(valuesJsonFinvDet
														.remove("[,]"));
										arFinvDet.add(valuesJsonFinvDet
												.toString());

									} catch (Exception e) {
									}
								}
								/*
								 * arrayLength = 7; progressHandler
								 * .sendMessage(
								 * progressHandler.obtainMessage());
								 */
							}
						}
						checkNetworkUploading();
						String strFH = arFinvHed.toString();
						String strFD = arFinvDet.toString();

						if (selectInvHeadDetails.getCount() <= 0) {
							Log.v(TAG, "ARRAY 1" + strFH + "/" + strFD);
						} else {
							strFH = strFH.replace("[", "");
							strFH = strFH.replace("]", "");
							strFD = strFD.replace("[", "");
							strFD = strFD.replace("]", "");
							// PDADBWebServiceM
							HttpPost request = new HttpPost(
									connectionURL
											+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/insertFInvHed");
							JSONStringer userJson = null;
							try {
								userJson = new JSONStringer().object()
										.key("fHed").value(strFH).key("fDet")
										.value(strFD);
							} catch (Exception e) {
							}

							StringEntity entity = null;
							try {
								// String repval = userJson.toString() + "}" +
								// ",UTF-8";
								String format1 = userJson.toString().replace(
										"[", "");
								String format2 = format1.replace("]", "");
								String format3 = format2.replace("\\", "");

								String format4 = "\"fHed\":\"";
								// String ggg = ",\"fDet\":\"";
								String format5 = "\",\"fDet\":\"";

								String format6 = format3.replace(format4,
										"\"fHed\":[");
								String format7 = format6.replace(format5,
										"],\"fDet\":[");
								format7 = format7 + "}";
								String dj = format7.replace("\"}\"}", "\"}]}");

								Log.v(TAG,
										"****************************************\n");
								Log.v(TAG, "JSON - Request: =" + dj);

								entity = new StringEntity(dj, "UTF-8");
							} catch (UnsupportedEncodingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							entity.setContentEncoding(new BasicHeader(
									HTTP.CONTENT_TYPE, "application/json"));
							entity.setContentType("application/json");
							request.setEntity(entity);

							// Send request to WCF service
							DefaultHttpClient httpClient = new DefaultHttpClient();

							try {
								Log.e("response", "connect");
								HttpResponse response = httpClient
										.execute(request);
								// Log.e("RES DJ1:", "RES DJ1:" +
								// response.toString());
								// ===========================================================
								HttpEntity entitye = response.getEntity();
								is = entitye.getContent();
								if (is != null) {
									int resval = 200;
									try {
										BufferedReader reader = new BufferedReader(
												new InputStreamReader(is,
														"iso-8859-1"), 8);
										sb = new StringBuilder();
										sb.append(reader.readLine() + "\n");
										String line = "0";
										while ((line = reader.readLine()) != null) {
											sb.append(line + "\n");
										}
										is.close();
										String result = sb.toString();
										Log.v(TAG, "CHKQUERY: =" + result);
										String result1 = result.replace("\"",
												"");
										// int result1Val =
										// Integer.parseInt(result1.trim());

										if (result1.trim().equals("200")) {
											Log.e("RES DJ3:", "RESULT 200 P1:"
													+ result1);
											ContentValues finvhedSynUpdateVal = new ContentValues();
											finvhedSynUpdateVal.put(
													"invhedSync", "1");
											mydb.update(INV_HEADER,
													finvhedSynUpdateVal,
													"invhedSync ='0'", null);
											ContentValues finvdetSynUpdateVal = new ContentValues();
											finvdetSynUpdateVal.put(
													"invdetSync", "1");
											mydb.update(INV_DETAILS,
													finvdetSynUpdateVal,
													"invdetSync ='0'", null);
											String fInvHedCountStr = Integer
													.toString(fInvHedCount);
											SIupSummary = "(SI -"
													+ fInvHedCountStr + "/"
													+ fInvHedCountStr + ")";
										} else if (result1.trim()
												.equals("null")) {
											Log.e("RES DJ2:",
													"RESULT ELSE NULL");
										}

										else {
											Log.v(TAG, "Responce XXXX :"
													+ result);
											String result12 = result.replace(
													"\",", "");
											String result13 = result12.replace(
													"\"", "");
											String result14 = result13.replace(
													"\\", "");
											String result15 = result14.replace(
													"200,", "");
											String[] items = result15
													.split(",");
											List<String> container = Arrays
													.asList(items);
											List<String> android = new ArrayList<String>(
													container);
											Log.e("RES DJ2:",
													"RESULT ELSE 200 :"
															+ android);
											// Getting Iterator from List
											Iterator<String> iteratorSI = android
													.iterator();
											try {
												selectInvHeadDetailsReChk = mydb
														.query(INV_HEADER,
																null,
																"invhedSync ='0'",
																null, null,
																null, null);
											} catch (Exception e) {
											}
											try {
												selectInvDetailsDataReChk = mydb
														.query(INV_DETAILS,
																null,
																"invdetSync ='0'",
																null, null,
																null, null);
											} catch (Exception e) {
											}
											int i = 1;
											while (iteratorSI.hasNext()) {

												ReadRefErrorUpload = iteratorSI
														.next();

												try {
													Log.e("RES DJ2:",
															"SYNC FAIL HED 7 :"
																	+ ReadRefErrorUpload);
													selectInvHeadDetailsReChk = mydb
															.query(INV_HEADER,
																	null,
																	"RefNo ='"
																			+ ReadRefErrorUpload
																					.trim()
																			+ "'",
																	null, null,
																	null, null);
												} catch (Exception e) {
												}
												try {
													Log.e("RES DJ2:",
															"SYNC FAIL DET 7 :"
																	+ ReadRefErrorUpload);
													selectInvDetailsDataReChk = mydb
															.query(INV_DETAILS,
																	null,
																	"RefNo ='"
																			+ ReadRefErrorUpload
																					.trim()
																			+ "'",
																	null, null,
																	null, null);
												} catch (Exception e) {
												}

												Log.e("RES DJ2:",
														"CHK HED:"
																+ selectInvHeadDetailsReChk
																		.getCount()
																+ " = " + i);
												Log.e("RES DJ2:",
														"CHK DET:"
																+ selectInvDetailsDataReChk
																		.getCount()
																+ " = " + i);

												if (selectInvHeadDetailsReChk != null) {
													if (selectInvHeadDetailsReChk
															.getCount() > 0) {
														while (selectInvHeadDetailsReChk
																.moveToNext()) {
															String syncUpdateHedSI = selectInvHeadDetailsReChk
																	.getString(1);
															ContentValues finvHedSynUpdaterall = new ContentValues();
															Log.e("RES DJ2:",
																	"SYNC FAIL 7 UPDATE HED:"
																			+ syncUpdateHedSI);
															finvHedSynUpdaterall
																	.put("invhedSync",
																			"7");
															mydb.update(
																	INV_HEADER,
																	finvHedSynUpdaterall,
																	"RefNo ='"
																			+ syncUpdateHedSI
																			+ "'",
																	null);
														}
													}
													// selectInvHeadDetailsReChk.close();
												}

												if (selectInvDetailsDataReChk != null) {
													if (selectInvDetailsDataReChk
															.getCount() > 0) {
														while (selectInvDetailsDataReChk
																.moveToNext()) {
															String syncUpdateDetSI = selectInvDetailsDataReChk
																	.getString(1);
															ContentValues finvdetSynUpdaterall = new ContentValues();
															Log.e("RES DJ2:",
																	"SYNC FAIL 7 UPDATE DET:"
																			+ syncUpdateDetSI);
															finvdetSynUpdaterall
																	.put("invdetSync",
																			"7");
															mydb.update(
																	INV_DETAILS,
																	finvdetSynUpdaterall,
																	"RefNo ='"
																			+ syncUpdateDetSI
																			+ "'",
																	null);
														}
													}
													// selectInvHeadDetailsReChk.close();
												}
												i = i + 1;
												fInvHedCountFail = fInvHedCountFail + 1;
												String fInvHedCountStr = Integer
														.toString(fInvHedCount);
												int uploadSuccess = fInvHedCount
														- fInvHedCountFail;
												String fInvHedCountStrFail = Integer
														.toString(fInvHedCountFail);
												String fInvHedCountStrSuccess = Integer
														.toString(uploadSuccess);

												SIupSummary = "(SI -"
														+ fInvHedCountStrSuccess
														+ "/" + fInvHedCountStr
														+ ")";
												// iteratorSI.next();
											}

											iteratorSI.remove();
											try {
												selectInvHeadDetailsUpdate = mydb
														.query(INV_HEADER,
																null,
																"invhedSync ='0'",
																null, null,
																null, null);
											} catch (Exception e) {
											}
											try {
												selectInvDetailsDataUpdate = mydb
														.query(INV_DETAILS,
																null,
																"invdetSync ='0'",
																null, null,
																null, null);
											} catch (Exception e) {
											}

											if (selectInvHeadDetailsUpdate != null) {
												if (selectInvHeadDetailsUpdate
														.getCount() > 0) {
													while (selectInvHeadDetailsUpdate
															.moveToNext()) {
														String mainRefNoHed = selectInvHeadDetailsUpdate
																.getString(1);
														Log.e("RES DJ2:",
																"SYNC OK HED :"
																		+ mainRefNoHed);
														ContentValues finvhedSynUpdaterall = new ContentValues();
														finvhedSynUpdaterall
																.put("invhedSync",
																		"1");
														mydb.update(
																INV_HEADER,
																finvhedSynUpdaterall,
																"RefNo ='"
																		+ mainRefNoHed
																		+ "'",
																null);
													}
												}
											}
											if (selectInvDetailsDataUpdate != null) {
												if (selectInvDetailsDataUpdate
														.getCount() > 0) {
													while (selectInvDetailsDataUpdate
															.moveToNext()) {
														String mainRefNoDet = selectInvDetailsDataUpdate
																.getString(1);
														Log.e("RES DJ2:",
																"SYNC OK DET :"
																		+ mainRefNoDet);
														ContentValues finvdetSynUpdaterall = new ContentValues();
														finvdetSynUpdaterall
																.put("invdetSync",
																		"1");
														mydb.update(
																INV_DETAILS,
																finvdetSynUpdaterall,
																"RefNo ='"
																		+ mainRefNoDet
																		+ "'",
																null);
													}
												}
											}

											try {
												selectInvHeadDetailsChkFail = mydb
														.query(INV_HEADER,
																null,
																"invhedSync ='7'",
																null, null,
																null, null);
											} catch (Exception e) {
											}
											try {
												selectInvDetailsDataChkFail = mydb
														.query(INV_DETAILS,
																null,
																"invdetSync ='7'",
																null, null,
																null, null);
											} catch (Exception e) {
											}

											if (selectInvHeadDetailsChkFail != null) {
												if (selectInvHeadDetailsChkFail
														.getCount() > 0) {
													while (selectInvHeadDetailsChkFail
															.moveToNext()) {

														String mainRefNoHedFail = selectInvHeadDetailsChkFail
																.getString(1);
														Log.e("RES DJ2:",
																"SYNC FAIL UPDATE HED :"
																		+ mainRefNoHedFail);
														ContentValues finvhedSynUpdaterallFail = new ContentValues();
														finvhedSynUpdaterallFail
																.put("invhedSync",
																		"0");
														mydb.update(
																INV_HEADER,
																finvhedSynUpdaterallFail,
																"RefNo ='"
																		+ mainRefNoHedFail
																		+ "'",
																null);
													}
												}
											}
											if (selectInvDetailsDataChkFail != null) {
												if (selectInvDetailsDataChkFail
														.getCount() > 0) {
													while (selectInvDetailsDataChkFail
															.moveToNext()) {
														String mainRefNoDetFail = selectInvDetailsDataChkFail
																.getString(1);
														Log.e("RES DJ2:",
																"SYNC FAIL UPDATE DET :"
																		+ mainRefNoDetFail);
														ContentValues finvdetSynUpdaterallFail = new ContentValues();
														finvdetSynUpdaterallFail
																.put("invdetSync",
																		"0");
														mydb.update(
																INV_DETAILS,
																finvdetSynUpdaterallFail,
																"RefNo ='"
																		+ mainRefNoDetFail
																		+ "'",
																null);
													}
												}
											}
										}

									} catch (Exception e1) {
										e1.printStackTrace();
									}
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
							arFinvHed.clear();
							arFinvDet.clear();

						}

					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}
			}

			// *******Sales Order Invoice Uploading Start********
			checkNetworkUploading();

			/* fOrdHedCount = selectOrderHeader.getCount(); */
			Cursor getRecordFordHed = null;
			try {
				getRecordFordHed = mydb.query(STOCK_ORDER_HEAD, null,
						"stordhedSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}
			if (getRecordFordHed != null) {
				if (getRecordFordHed.getCount() > 0) {
					while (getRecordFordHed.moveToNext()) {
						fOrdHedCount = getRecordFordHed.getCount();
						String RefNoUploading = getRecordFordHed.getString(16);
						Log.v(TAG, "Array fOrdHed :" + RefNoUploading);

						// *******Sales Orders Invoice********
						try {
							selectOrderHeader = mydb.query(STOCK_ORDER_HEAD,
									null, "RefNo ='" + RefNoUploading + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						try {
							selectOrderDetails = mydb.query(STOCK_ORDER_DETAIL,
									null, "RefNo ='" + RefNoUploading + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (selectOrderHeader != null) {
							if (selectOrderHeader.getCount() > 0) {
								while (selectOrderHeader.moveToNext()) {
									// FStoOrdersHedIndex =
									// selectOrderHeader.getString(0);
									String AddMach = selectOrderHeader
											.getString(1);
									String AddUser = selectOrderHeader
											.getString(2);
									String AreaCode = selectOrderHeader
											.getString(3);
									String CostCode = selectOrderHeader
											.getString(4);
									String CurCode = selectOrderHeader
											.getString(5);
									String CurRate = selectOrderHeader
											.getString(6);
									String DealCode = selectOrderHeader
											.getString(7);
									String DebCode = selectOrderHeader
											.getString(8);
									String InvAmt = selectOrderHeader
											.getString(9);

									String InvFlg = selectOrderHeader
											.getString(11);
									String LocCode = selectOrderHeader
											.getString(12);
									String ManuRef = selectOrderHeader
											.getString(13);
									String OutDis = selectOrderHeader
											.getString(14);
									String RecordId = selectOrderHeader
											.getString(15);
									String RefNo = selectOrderHeader
											.getString(16);
									String Remarks = selectOrderHeader
											.getString(17);
									String RepCode = selectOrderHeader
											.getString(18);
									String RouteCode = selectOrderHeader
											.getString(19);
									String TotMkrAmt = selectOrderHeader
											.getString(20);
									String TotalAmt = selectOrderHeader
											.getString(21);
									String InvDis = "0", TotalDis = "0";
									double InvDisVal = 0.0, TotalDisVal = 0.0;
									try {
										InvDis = selectOrderHeader
												.getString(10);
										InvDisVal = Double.parseDouble(InvDis
												.replaceAll("[,]", ""));
										TotalDis = selectOrderHeader
												.getString(22);
										TotalDisVal = Double
												.parseDouble(TotalDis
														.replaceAll("[,]", ""));
									} catch (Exception e) {

									}

									String TranBatch = selectOrderHeader
											.getString(23);
									String TxnType = selectOrderHeader
											.getString(24);
									String UnOvAmt = selectOrderHeader
											.getString(25);
									String prtcopy = selectOrderHeader
											.getString(26);
									String TxnDate = selectOrderHeader
											.getString(27);
									String outDisVal = selectOrderHeader
											.getString(30);
									UploadodAddDate = selectOrderHeader
											.getString(31);
									String DeliverAddDate = selectOrderHeader
											.getString(32);

									try {
										date = originalFormat
												.parse(DeliverAddDate
														.replaceAll(
																"[-+/.^:,]",
																" "));
										DeliverAddDate = targetFormat
												.format(date);

									} catch (ParseException ex) {
									}

									// Log.v(TAG, "DDDD :" + UploadodAddDate);
									try {
										if (UploadodAddDate.equals(null)) {
											UploadodAddDate = getAddDateTimeString()
													.toString();
										}
									} catch (Exception ex) {
										UploadodAddDate = getAddDateTimeString()
												.toString();
									}
									double outDisValue = Double
											.parseDouble(outDisVal.replaceAll(
													"[,]", ""));
									// Line Items Discount
									double LineItemsDis = TotalDisVal
											- (InvDisVal + outDisValue);
									String LineItemsDisString = Double
											.toString(LineItemsDis);

									try {
										date = originalFormat.parse(TxnDate
												.replaceAll("[-+/.^:,]", " "));
										TxnDate = targetFormat.format(date);

									} catch (ParseException ex) {
										TxnDate = "1900-01-01";
									}

									// Create values JSONArray
									JSONArray valuesarrayFordHed = new JSONArray();
									try {
										// Create values jsonObject
										JSONObject valuesJsonFOrdHed = new JSONObject();
										valuesJsonFOrdHed.put("RefNo", RefNo);
										valuesJsonFOrdHed.put("TxnDate",
												TxnDate);
										valuesJsonFOrdHed.put("ManuRef",
												ManuRef);
										valuesJsonFOrdHed.put("DelvDate",
												DeliverAddDate);
										valuesJsonFOrdHed.put("DealCode",
												AgentDealCode);
										valuesJsonFOrdHed.put("RepCode",
												RepCode);
										valuesJsonFOrdHed.put("AreaCode",
												AreaCode);
										valuesJsonFOrdHed.put("RouteCode",
												RepRouteCode);
										valuesJsonFOrdHed.put("DebCode",
												DebCode);
										valuesJsonFOrdHed.put("LocCode",
												LocCode);
										valuesJsonFOrdHed.put("Remarks",
												Remarks);
										valuesJsonFOrdHed.put("CostCode",
												CostCode);
										valuesJsonFOrdHed.put("CurCode",
												CurCode);
										valuesJsonFOrdHed.put("CurRate",
												CurRate);
										valuesJsonFOrdHed.put("TxnType",
												TxnType);
										valuesJsonFOrdHed.put("InvAmt",
												InvAmt.replaceAll("[,]", ""));
										valuesJsonFOrdHed.put("OutDis",
												OutDis.replaceAll("[,]", ""));
										valuesJsonFOrdHed.put("InvDis",
												InvDis.replaceAll("[,]", ""));
										valuesJsonFOrdHed
												.put("TotMkrAmt", TotMkrAmt
														.replaceAll("[,]", ""));
										valuesJsonFOrdHed.put("UnOvAmt",
												UnOvAmt.replaceAll("[,]", ""));
										valuesJsonFOrdHed.put("TotalDis",
												TotalDis.replaceAll("[,]", ""));
										valuesJsonFOrdHed.put("TotalItmDis",
												LineItemsDisString.replaceAll(
														"[,]", ""));
										valuesJsonFOrdHed.put("TotalAmt",
												TotalAmt.replaceAll("[,]", ""));
										valuesJsonFOrdHed.put("AddUser",
												AddUser);
										valuesJsonFOrdHed.put("AddMach",
												AddMach);
										valuesJsonFOrdHed.put("prtcopy",
												prtcopy);
										valuesJsonFOrdHed.put("InvFlg", InvFlg);
										valuesJsonFOrdHed.put("RecordId",
												RecordId);
										valuesJsonFOrdHed.put("TranBatch",
												TranBatch);
										valuesJsonFOrdHed.put("OutDisVal",
												outDisValue);
										valuesJsonFOrdHed.put("AddDate",
												UploadodAddDate);
										valuesJsonFOrdHed.put("DbName",
												currentUserServerDB);

										valuesarrayFordHed
												.put(valuesJsonFOrdHed
														.remove("[,]"));
										arFordHed.add(valuesJsonFOrdHed
												.toString());
									} catch (Exception Ex) {

									}

								}
								/*
								 * arrayLength = 7; progressHandler
								 * .sendMessage(
								 * progressHandler.obtainMessage());
								 */
							}
						}

						checkNetworkUploading();
						if (selectOrderDetails != null) {
							if (selectOrderDetails.getCount() > 0) {
								while (selectOrderDetails.moveToNext()) {
									// FStOrderDetIndex =
									// selectOrderDetails.getString(0);
									String Amt = selectOrderDetails
											.getString(1);
									String BAmt = selectOrderDetails
											.getString(2);
									String BDisAmt = selectOrderDetails
											.getString(3);
									String BSellPrice = selectOrderDetails
											.getString(4);
									String BTSellPrice = selectOrderDetails
											.getString(5);
									String BTaxAmt = selectOrderDetails
											.getString(6);
									String BalQty = selectOrderDetails
											.getString(7);
									String CaseQty = selectOrderDetails
											.getString(8);
									String CostPrice = selectOrderDetails
											.getString(9);
									String DisAmt = selectOrderDetails
											.getString(10);
									String DisPer = selectOrderDetails
											.getString(11);
									String Itemcode = selectOrderDetails
											.getString(12);
									String PiceQty = selectOrderDetails
											.getString(13);
									String Qty = selectOrderDetails
											.getString(14);
									String ReaCode = selectOrderDetails
											.getString(15);
									String RecordId = selectOrderDetails
											.getString(16);
									String RefNo = selectOrderDetails
											.getString(17);
									String SellPrice = selectOrderDetails
											.getString(18);
									String SeqNo = selectOrderDetails
											.getString(19);
									String TSellPrice = selectOrderDetails
											.getString(20);
									String TaxAmt = selectOrderDetails
											.getString(21);
									String TxnType = selectOrderDetails
											.getString(22);
									String Txnseqno = selectOrderDetails
											.getString(23);
									String Type = selectOrderDetails
											.getString(24);
									String TxnDate = selectOrderDetails
											.getString(25);
									String itemdisper = selectOrderDetails
											.getString(27);
									String itemdisperval = "0", DisValueAmtCalStr = "0";
									try {
										itemdisperval = selectOrderDetails
												.getString(28);
										double totlineItemDis = Double
												.parseDouble(BDisAmt
														.replaceAll("[,]", ""));
										double DisPerAmount = Double
												.parseDouble(itemdisperval
														.replaceAll("[,]", ""));
										double DisValueAmtCal = totlineItemDis
												- DisPerAmount;
										DisValueAmtCalStr = Double
												.toString(DisValueAmtCal);
									} catch (Exception e) {

									}

									try {
										date = originalFormat.parse(TxnDate
												.replaceAll("[-+/.^:,]", " "));
										TxnDate = targetFormat.format(date);
									} catch (ParseException ex) {
										TxnDate = "1900-01-01";
									}

									// Create values JSONArray
									JSONArray valuesarrayFordDet = new JSONArray();
									try {
										// Create values jsonObject
										JSONObject valuesJsonFOrdDet = new JSONObject();
										valuesJsonFOrdDet.put("RefNo", RefNo);
										valuesJsonFOrdDet.put("TxnDate",
												TxnDate);
										valuesJsonFOrdDet.put("TxnType",
												TxnType);
										valuesJsonFOrdDet.put("SeqNo", SeqNo);
										valuesJsonFOrdDet.put("Itemcode",
												Itemcode);
										valuesJsonFOrdDet.put("Txnseqno",
												Txnseqno);
										valuesJsonFOrdDet
												.put("SellPrice", SellPrice
														.replaceAll("[,]", ""));
										valuesJsonFOrdDet.put("BSellPrice",
												BSellPrice
														.replaceAll("[,]", ""));
										valuesJsonFOrdDet.put("TSellPrice",
												TSellPrice
														.replaceAll("[,]", ""));
										valuesJsonFOrdDet.put("BTSellPrice",
												BTSellPrice.replaceAll("[,]",
														""));
										valuesJsonFOrdDet
												.put("CostPrice", CostPrice
														.replaceAll("[,]", ""));
										valuesJsonFOrdDet.put("CaseQty",
												CaseQty);
										valuesJsonFOrdDet.put("Type", Type);
										valuesJsonFOrdDet.put("PiceQty",
												PiceQty.replaceAll("[,]", ""));
										valuesJsonFOrdDet.put("Qty", Qty);
										valuesJsonFOrdDet.put("BalQty",
												BalQty.replaceAll("[,]", ""));
										valuesJsonFOrdDet.put("DisPer", DisPer);
										valuesJsonFOrdDet.put("DisAmt",
												DisAmt.replaceAll("[,]", ""));
										valuesJsonFOrdDet.put("BDisAmt",
												BDisAmt);
										valuesJsonFOrdDet.put("TaxAmt",
												TaxAmt.replaceAll("[,]", ""));
										valuesJsonFOrdDet.put("BTaxAmt",
												BTaxAmt.replaceAll("[,]", ""));
										valuesJsonFOrdDet.put("Amt", Amt);
										valuesJsonFOrdDet.put("BAmt",
												BAmt.replaceAll("[,]", ""));
										valuesJsonFOrdDet.put("ReaCode",
												ReaCode);
										valuesJsonFOrdDet.put("DisPerAmt",
												itemdisperval.replaceAll("[,]",
														""));
										valuesJsonFOrdDet.put("DisValAmt",
												DisValueAmtCalStr.replaceAll(
														"[,]", ""));
										valuesJsonFOrdDet.put("DbName",
												currentUserServerDB);

										valuesarrayFordDet
												.put(valuesJsonFOrdDet
														.remove("[,]"));
										arFordDet.add(valuesJsonFOrdDet
												.toString());
									} catch (Exception ex) {

									}
								}
								/*
								 * arrayLength = 7; progressHandler
								 * .sendMessage(
								 * progressHandler.obtainMessage());
								 */
							}
						}

						checkNetworkUploading();
						String strFORDH = arFordHed.toString();
						String strFORDD = arFordDet.toString();

						if (selectOrderHeader.getCount() <= 0) {
							Log.v(TAG, "ARRAY 2" + strFORDH + "/" + strFORDD);
						} else {
							strFORDH = strFORDH.replace("[", "");
							strFORDH = strFORDH.replace("]", "");
							strFORDD = strFORDD.replace("[", "");
							strFORDD = strFORDD.replace("]", "");
							// PDADBWebServiceM
							HttpPost requestSOrd = new HttpPost(
									connectionURL
											+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/updateFOrdHed");
							JSONStringer userJsonSOrd = null;
							try {
								userJsonSOrd = new JSONStringer().object()
										.key("fOHed").value(strFORDH)
										.key("fODet").value(strFORDD);
							} catch (Exception e) {
							}

							StringEntity entityFSO = null;
							try {
								// String repval = userJson.toString() + "}" +
								// ",UTF-8";
								String formatso1 = userJsonSOrd.toString()
										.replace("[", "");
								String formatso2 = formatso1.replace("]", "");
								String formatso3 = formatso2.replace("\\", "");

								String formatso4 = "\"fOHed\":\"";
								// String ggg = ",\"fDet\":\"";
								String formatso5 = "\",\"fODet\":\"";

								String formatso6 = formatso3.replace(formatso4,
										"\"fOHed\":[");
								String formatso7 = formatso6.replace(formatso5,
										"],\"fODet\":[");
								formatso7 = formatso7 + "}";
								String sendReqSO = formatso7.replace("\"}\"}",
										"\"}]}");
								entityFSO = new StringEntity(sendReqSO, "UTF-8");
							} catch (UnsupportedEncodingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							entityFSO.setContentEncoding(new BasicHeader(
									HTTP.CONTENT_TYPE, "application/json"));
							entityFSO.setContentType("application/json");
							requestSOrd.setEntity(entityFSO);

							// Send request to WCF service
							DefaultHttpClient httpClientSO = new DefaultHttpClient();

							try {
								Log.e("response", "connect");
								HttpResponse responseSO = httpClientSO
										.execute(requestSOrd);

								// ===========================================================
								HttpEntity entitySO = responseSO.getEntity();
								is = entitySO.getContent();
								if (is != null) {

									try {
										BufferedReader reader_so = new BufferedReader(
												new InputStreamReader(is,
														"iso-8859-1"), 8);
										sb = new StringBuilder();
										sb.append(reader_so.readLine() + "\n");
										String line = "0";
										while ((line = reader_so.readLine()) != null) {
											sb.append(line + "\n");
										}
										is.close();
										String result_so = sb.toString();
										String result_so1 = result_so.replace(
												"\"", "");
										Log.e("RES DJ1:", "XXXXX :"
												+ result_so1);
										if (result_so1.trim().equals("200")) {
											ContentValues fordhedSynUpdateVal = new ContentValues();
											fordhedSynUpdateVal.put(
													"stordhedSync", "1");
											mydb.update(STOCK_ORDER_HEAD,
													fordhedSynUpdateVal,
													"stordhedSync ='0'", null);

											ContentValues forddetSynUpdateVal = new ContentValues();
											forddetSynUpdateVal.put(
													"storddetSync", "1");
											mydb.update(STOCK_ORDER_DETAIL,
													forddetSynUpdateVal,
													"storddetSync ='0'", null);

											String fInvOrdCountStr = Integer
													.toString(fOrdHedCount);
											SOupSummary = "(SO -"
													+ fInvOrdCountStr + "/"
													+ fInvOrdCountStr + ")";
										} else if (result_so1.trim().equals(
												"null")) {
											Log.e("RES DJ2:",
													"RESULT ELSE NULL");
										} else {
											String result12 = result_so
													.replace("\",", "");
											String result13 = result12.replace(
													"\"", "");
											String result14 = result13.replace(
													"\\", "");
											String result15 = result14.replace(
													"200,", "");
											String[] items = result15
													.split(",");
											List<String> container = Arrays
													.asList(items);
											List<String> android = new ArrayList<String>(
													container);
											Log.e("RES DJ2:",
													"RESULT ELSE 200 :"
															+ android);
											// Getting Iterator from List
											Iterator<String> iteratorSO = android
													.iterator();
											Cursor selectStOrdHeadDetailsReChk = null, selectStOrdDetailsDataReChk = null;
											try {
												selectStOrdHeadDetailsReChk = mydb
														.query(STOCK_ORDER_HEAD,
																null,
																"stordhedSync ='0'",
																null, null,
																null, null);
											} catch (Exception e) {
											}
											try {
												selectStOrdDetailsDataReChk = mydb
														.query(STOCK_ORDER_DETAIL,
																null,
																"storddetSync ='0'",
																null, null,
																null, null);
											} catch (Exception e) {
											}
											while (iteratorSO.hasNext()) {
												String ReadRefNumbers = iteratorSO
														.next();
												Log.e("RES DJ2:",
														"UploadError REF:"
																+ ReadRefNumbers);
												if (selectStOrdHeadDetailsReChk != null) {
													if (selectStOrdHeadDetailsReChk
															.getCount() > 0) {
														while (selectStOrdHeadDetailsReChk
																.moveToNext()) {
															String mainRefNoErrorHed = selectStOrdHeadDetailsReChk
																	.getString(16);
															ContentValues fStOrdhedSynUpdaterall = new ContentValues();
															fStOrdhedSynUpdaterall
																	.put("stordhedSync",
																			"7");
															mydb.update(
																	STOCK_ORDER_HEAD,
																	fStOrdhedSynUpdaterall,
																	"RefNo ='"
																			+ mainRefNoErrorHed
																			+ "'",
																	null);
														}
													}
												}

												if (selectStOrdDetailsDataReChk != null) {
													if (selectStOrdDetailsDataReChk
															.getCount() > 0) {
														while (selectStOrdDetailsDataReChk
																.moveToNext()) {
															String mainRefNoErrorDet = selectStOrdDetailsDataReChk
																	.getString(17);
															ContentValues fStOrddetSynUpdaterall = new ContentValues();
															fStOrddetSynUpdaterall
																	.put("storddetSync",
																			"7");
															mydb.update(
																	STOCK_ORDER_DETAIL,
																	fStOrddetSynUpdaterall,
																	"RefNo ='"
																			+ mainRefNoErrorDet
																			+ "'",
																	null);
														}
													}
												}

												fOrdHedCountFail = fOrdHedCountFail + 1;
												String fInvOrdCountStr = Integer
														.toString(fOrdHedCount);
												int soSuccessUpload = fOrdHedCount
														- fOrdHedCountFail;
												String fInvOrdCountStrFail = Integer
														.toString(fOrdHedCountFail);
												String fInvOrdCountStrSuccess = Integer
														.toString(soSuccessUpload);
												SOupSummary = "(SO -"
														+ fInvOrdCountStrSuccess
														+ "/" + fInvOrdCountStr
														+ ")";
												iteratorSO.remove();
											}

											Cursor selectStOrdHeadDetailsUpdate = null, selectStOrdDetailsDataUpdate = null;
											try {
												selectStOrdHeadDetailsUpdate = mydb
														.query(STOCK_ORDER_HEAD,
																null,
																"stordhedSync ='0'",
																null, null,
																null, null);
											} catch (Exception e) {
											}
											try {
												selectStOrdDetailsDataUpdate = mydb
														.query(STOCK_ORDER_DETAIL,
																null,
																"storddetSync ='0'",
																null, null,
																null, null);
											} catch (Exception e) {
											}

											if (selectStOrdHeadDetailsUpdate != null) {
												if (selectStOrdHeadDetailsUpdate
														.getCount() > 0) {
													while (selectStOrdHeadDetailsUpdate
															.moveToNext()) {
														String mainRefNoHed = selectStOrdHeadDetailsUpdate
																.getString(16);
														ContentValues fStOrdhedSynUpdaterall = new ContentValues();
														fStOrdhedSynUpdaterall
																.put("stordhedSync",
																		"1");
														mydb.update(
																STOCK_ORDER_HEAD,
																fStOrdhedSynUpdaterall,
																"RefNo ='"
																		+ mainRefNoHed
																		+ "'",
																null);
													}
												}
											}
											if (selectStOrdDetailsDataUpdate != null) {
												if (selectStOrdDetailsDataUpdate
														.getCount() > 0) {
													while (selectStOrdDetailsDataUpdate
															.moveToNext()) {
														String mainRefNoDet = selectStOrdDetailsDataUpdate
																.getString(17);
														ContentValues fStOrddetSynUpdaterall = new ContentValues();
														fStOrddetSynUpdaterall
																.put("storddetSync",
																		"1");
														mydb.update(
																STOCK_ORDER_DETAIL,
																fStOrddetSynUpdaterall,
																"RefNo ='"
																		+ mainRefNoDet
																		+ "'",
																null);
													}
												}
											}

											Cursor selectStOrdHeadDetailsChkFail = null, selectStOrdDetailsDataChkFail = null;
											try {
												selectStOrdHeadDetailsChkFail = mydb
														.query(STOCK_ORDER_HEAD,
																null,
																"stordhedSync ='7'",
																null, null,
																null, null);
											} catch (Exception e) {
											}
											try {
												selectStOrdDetailsDataChkFail = mydb
														.query(STOCK_ORDER_DETAIL,
																null,
																"storddetSync ='7'",
																null, null,
																null, null);
											} catch (Exception e) {
											}

											if (selectStOrdHeadDetailsChkFail != null) {
												if (selectStOrdHeadDetailsChkFail
														.getCount() > 0) {
													while (selectStOrdHeadDetailsChkFail
															.moveToNext()) {
														String mainRefNoHedFail = selectStOrdHeadDetailsChkFail
																.getString(16);
														ContentValues fStOrdhedSynUpdaterallFail = new ContentValues();
														fStOrdhedSynUpdaterallFail
																.put("stordhedSync",
																		"0");
														mydb.update(
																STOCK_ORDER_HEAD,
																fStOrdhedSynUpdaterallFail,
																"RefNo ='"
																		+ mainRefNoHedFail
																		+ "'",
																null);
													}
												}
											}
											if (selectStOrdDetailsDataChkFail != null) {
												if (selectStOrdDetailsDataChkFail
														.getCount() > 0) {
													while (selectStOrdDetailsDataChkFail
															.moveToNext()) {
														String mainRefNoDetFail = selectStOrdDetailsDataChkFail
																.getString(17);
														ContentValues fStOrddetSynUpdaterallFail = new ContentValues();
														fStOrddetSynUpdaterallFail
																.put("storddetSync",
																		"0");
														mydb.update(
																STOCK_ORDER_DETAIL,
																fStOrddetSynUpdaterallFail,
																"RefNo ='"
																		+ mainRefNoDetFail
																		+ "'",
																null);
													}
												}
											}

										}

									} catch (Exception e1) {
										e1.printStackTrace();
									}
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
							arFordHed.clear();
							arFordDet.clear();
						}

					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}

			}

			// *************Upload Cancel Invoice*********
			checkNetworkUploading();
			if (selectSIcancelHedDetDetails != null) {
				if (selectSIcancelHedDetDetails.getCount() > 0) {
					while (selectSIcancelHedDetDetails.moveToNext()) {
						String RefNo = selectSIcancelHedDetDetails.getString(0);
						String RefNo1 = selectSIcancelHedDetDetails
								.getString(1);
						String InvType = selectSIcancelHedDetDetails
								.getString(2);
						String TxnDate = selectSIcancelHedDetDetails
								.getString(3);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String ManuRef = selectSIcancelHedDetDetails
								.getString(4);
						String DealCode = selectSIcancelHedDetDetails
								.getString(5);
						String RepCode = selectSIcancelHedDetDetails
								.getString(6);
						String AreaCode = selectSIcancelHedDetDetails
								.getString(7);
						String RouteCode = selectSIcancelHedDetDetails
								.getString(8);
						String DebCode = selectSIcancelHedDetDetails
								.getString(9);
						String LocCode = selectSIcancelHedDetDetails
								.getString(10);
						String Remarks = selectSIcancelHedDetDetails
								.getString(11);
						String CostCode = selectSIcancelHedDetDetails
								.getString(12);
						String CurCode = selectSIcancelHedDetDetails
								.getString(13);
						String CurRate = selectSIcancelHedDetDetails
								.getString(14);
						String TxnType = selectSIcancelHedDetDetails
								.getString(15);
						String InvAmt = selectSIcancelHedDetDetails
								.getString(16);
						String OutDis = selectSIcancelHedDetDetails
								.getString(17);
						String InvDis = selectSIcancelHedDetDetails
								.getString(18);
						String TotMkrAmt = selectSIcancelHedDetDetails
								.getString(19);
						String UnOvAmt = selectSIcancelHedDetDetails
								.getString(20);
						String TotalDis = selectSIcancelHedDetDetails
								.getString(21);
						String TotalAmt = selectSIcancelHedDetDetails
								.getString(22);
						String AddUser = selectSIcancelHedDetDetails
								.getString(23);
						String AddDateInvHead = selectSIcancelHedDetDetails
								.getString(24);
						try {
							date = originalFormat.parse(AddDateInvHead
									.replaceAll("[-+/.^:,]", " "));
							AddDateInvHead = targetFormat.format(date);

						} catch (ParseException ex) {
						}

						Log.v(TAG, "DDDD :" + UploadodAddDate);
						try {
							if (UploadodAddDate.equals(null)) {
								UploadodAddDate = getAddDateTimeString()
										.toString();
							}
						} catch (Exception ex) {
							UploadodAddDate = getAddDateTimeString().toString();
						}
						String AddMach = selectSIcancelHedDetDetails
								.getString(25);
						String prtcopy = selectSIcancelHedDetDetails
								.getString(26);
						String detRefno = selectSIcancelHedDetDetails
								.getString(27);
						String SeqNo = selectSIcancelHedDetDetails
								.getString(28);
						String Itemcode = selectSIcancelHedDetDetails
								.getString(29);
						String Txnseqno = selectSIcancelHedDetDetails
								.getString(30);
						String SellPrice = selectSIcancelHedDetDetails
								.getString(31);
						String BSellPrice = selectSIcancelHedDetDetails
								.getString(32);
						String TSellPrice = selectSIcancelHedDetDetails
								.getString(33);
						String BTSellPrice = selectSIcancelHedDetDetails
								.getString(34);
						String CostPrice = selectSIcancelHedDetDetails
								.getString(35);
						String CaseQty = selectSIcancelHedDetDetails
								.getString(36);
						String PiceQty = selectSIcancelHedDetDetails
								.getString(37);
						String Type = selectSIcancelHedDetDetails.getString(38);
						String Qty = selectSIcancelHedDetDetails.getString(39);
						String BalQty = selectSIcancelHedDetDetails
								.getString(40);
						String DisPer = selectSIcancelHedDetDetails
								.getString(41);
						String DisAmt = selectSIcancelHedDetDetails
								.getString(42);
						String BDisAmt = selectSIcancelHedDetDetails
								.getString(43);
						String DisPerAmt = selectSIcancelHedDetDetails
								.getString(44);
						String DisValAmt = selectSIcancelHedDetDetails
								.getString(45);
						String TaxAmt = selectSIcancelHedDetDetails
								.getString(46);
						String BTaxAmt = selectSIcancelHedDetDetails
								.getString(47);
						String Amt = selectSIcancelHedDetDetails.getString(48);
						String BAmt = selectSIcancelHedDetDetails.getString(49);
						String ReaCode = selectSIcancelHedDetDetails
								.getString(50);
						String Linkrec = selectSIcancelHedDetDetails
								.getString(51);

						String DelDate = selectSIcancelHedDetDetails
								.getString(24);
						try {
							date = originalFormat.parse(DelDate.replaceAll(
									"[-+/.^:,]", " "));
							DelDate = targetFormat.format(date);

						} catch (ParseException ex) {
							DelDate = "1900-01-01";
						}
						String DelType = "D";
						String DelMach = selectSIcancelHedDetDetails
								.getString(25);
						String DelUser = selectSIcancelHedDetDetails
								.getString(6);
						String DelReasn = "0";
						String Longitude = "0";
						String Latitude = "0";
						// Create values JSONArray
						JSONArray valuesarrayCanceledFHedDet = new JSONArray();
						try {
							// Create values jsonObject
							JSONObject valuesarrayCancelSIhedDet = new JSONObject();
							valuesarrayCancelSIhedDet.put("RefNo", RefNo);
							valuesarrayCancelSIhedDet.put("RefNo1", RefNo1);
							valuesarrayCancelSIhedDet.put("InvType", InvType);
							valuesarrayCancelSIhedDet.put("TxnDate", TxnDate);
							valuesarrayCancelSIhedDet.put("ManuRef", ManuRef);
							valuesarrayCancelSIhedDet.put("DealCode", DealCode);
							valuesarrayCancelSIhedDet.put("RepCode", RepCode);
							valuesarrayCancelSIhedDet.put("AreaCode", AreaCode);
							valuesarrayCancelSIhedDet.put("RouteCode",
									RouteCode);
							valuesarrayCancelSIhedDet.put("DebCode", DebCode);
							valuesarrayCancelSIhedDet.put("LocCode", LocCode);
							valuesarrayCancelSIhedDet.put("Remarks", Remarks);
							valuesarrayCancelSIhedDet.put("CostCode", CostCode);
							valuesarrayCancelSIhedDet.put("CurCode", CurCode);
							valuesarrayCancelSIhedDet.put("CurRate", CurRate);
							valuesarrayCancelSIhedDet.put("TxnType", TxnType);
							valuesarrayCancelSIhedDet.put("InvAmt", InvAmt);
							valuesarrayCancelSIhedDet.put("OutDis", OutDis);
							valuesarrayCancelSIhedDet.put("InvDis", InvDis);
							valuesarrayCancelSIhedDet.put("TotMkrAmt",
									TotMkrAmt);
							valuesarrayCancelSIhedDet.put("UnOvAmt", UnOvAmt);
							valuesarrayCancelSIhedDet.put("TotalItmDis",
									TotalDis);
							valuesarrayCancelSIhedDet.put("TotalDis", TotalDis);
							valuesarrayCancelSIhedDet.put("TotalAmt", TotalAmt);
							valuesarrayCancelSIhedDet.put("SeqNo", SeqNo);
							valuesarrayCancelSIhedDet.put("Itemcode", Itemcode);
							valuesarrayCancelSIhedDet.put("Txnseqno", Txnseqno);
							valuesarrayCancelSIhedDet.put("SellPrice",
									SellPrice);
							valuesarrayCancelSIhedDet.put("BSellPrice",
									BSellPrice);
							valuesarrayCancelSIhedDet.put("TSellPrice",
									TSellPrice);
							valuesarrayCancelSIhedDet.put("BTSellPrice",
									BTSellPrice);
							valuesarrayCancelSIhedDet.put("CostPrice",
									CostPrice);
							valuesarrayCancelSIhedDet.put("CaseQty", CaseQty);
							valuesarrayCancelSIhedDet.put("PiceQty", PiceQty);
							valuesarrayCancelSIhedDet.put("Type", Type);
							valuesarrayCancelSIhedDet.put("Qty", Qty);
							valuesarrayCancelSIhedDet.put("BalQty", BalQty);
							valuesarrayCancelSIhedDet.put("DisPer", DisPer);
							valuesarrayCancelSIhedDet.put("DisAmt", DisAmt);
							valuesarrayCancelSIhedDet.put("BDisAmt", BDisAmt);
							valuesarrayCancelSIhedDet.put("DisPerAmt",
									DisPerAmt);
							valuesarrayCancelSIhedDet.put("DisValAmt",
									DisValAmt);
							valuesarrayCancelSIhedDet.put("TaxAmt", TaxAmt);
							valuesarrayCancelSIhedDet.put("BTaxAmt", BTaxAmt);
							valuesarrayCancelSIhedDet.put("Amt", Amt);
							valuesarrayCancelSIhedDet.put("BAmt", BAmt);
							valuesarrayCancelSIhedDet.put("ReaCode", ReaCode);
							valuesarrayCancelSIhedDet.put("AddUser", AddUser);
							valuesarrayCancelSIhedDet.put("AddDate", TxnDate);
							valuesarrayCancelSIhedDet.put("AddMach", AddMach);
							valuesarrayCancelSIhedDet.put("prtcopy", prtcopy);
							valuesarrayCancelSIhedDet.put("DelDate", TxnDate);
							valuesarrayCancelSIhedDet.put("DelType", DelType);
							valuesarrayCancelSIhedDet.put("DelMach", DelMach);
							valuesarrayCancelSIhedDet.put("DelUser", DelUser);
							valuesarrayCancelSIhedDet.put("DelReasn", DelReasn);
							valuesarrayCancelSIhedDet.put("Linkrec", Linkrec);
							valuesarrayCancelSIhedDet.put("Longitude",
									Longitude);
							valuesarrayCancelSIhedDet.put("Latitude", Latitude);
							valuesarrayCancelSIhedDet.put("DbName",
									currentUserServerDB);
							valuesarrayCanceledFHedDet
									.put(valuesarrayCancelSIhedDet
											.remove("[,]"));
							arCanceleInvHedDet.add(valuesarrayCancelSIhedDet
									.toString());

						} catch (Exception e) {

						}
					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}
			}
			// Log.v(TAG, "arCanceleInvHedDet:" + arCanceleInvHedDet);
			// PDADBWebServiceM
			checkNetworkUploading();
			if (selectSIcancelHedDetDetails.getCount() <= 0) {
				Log.v(TAG, "ARRAY 3" + arCanceleInvHedDet);
			} else {
				HttpPost requestIInvDet = new HttpPost(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/insertlInvdet");
				JSONStringer userJsonlInvdet = null;
				try {
					userJsonlInvdet = new JSONStringer().object().key("fDet")
							.value(arCanceleInvHedDet);
				} catch (Exception e) {
				}

				StringEntity entitylInvdet = null;
				try {
					// String repval = userJson.toString() + "}" + ",UTF-8";
					String formatso1 = userJsonlInvdet.toString().replace("\\",
							"");
					String formatso2 = formatso1.replace("\"[{", "[{");
					String formatso3 = formatso2.replace("}]\"", "}]}");

					Log.v(TAG, "****************************************\n");
					Log.v(TAG, "JSON1 =" + formatso3);
					entitylInvdet = new StringEntity(formatso3, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				entitylInvdet.setContentEncoding(new BasicHeader(
						HTTP.CONTENT_TYPE, "application/json"));
				entitylInvdet.setContentType("application/json");
				requestIInvDet.setEntity(entitylInvdet);

				// Send request to WCF service
				DefaultHttpClient httpClientlInvdet = new DefaultHttpClient();

				try {
					Log.e("response", "connect");
					HttpResponse responselInvdet = httpClientlInvdet
							.execute(requestIInvDet);
					// Log.e("RES DJ1:", "RES DJ1:" +
					// responselInvdet.toString());
					// ===========================================================
					HttpEntity entity_lInvdet = responselInvdet.getEntity();
					is = entity_lInvdet.getContent();
					if (is != null) {

						try {
							BufferedReader reader_lInvdet = new BufferedReader(
									new InputStreamReader(is, "iso-8859-1"), 8);
							sb = new StringBuilder();
							sb.append(reader_lInvdet.readLine() + "\n");
							String line = "0";
							while ((line = reader_lInvdet.readLine()) != null) {
								sb.append(line + "\n");
							}
							is.close();
							String result_lInvdet = sb.toString();
							Log.e("RES DJ2:", "RESULT :" + result_lInvdet);
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				arCanceleInvHedDet.clear();
			}
			// ****************Upload Canceled Invoice Header/Details records
			// *************Upload Cancel Invoice*********
			checkNetworkUploading();
			if (selectSOcancelHedDetDetails != null) {
				if (selectSOcancelHedDetDetails.getCount() > 0) {
					while (selectSOcancelHedDetDetails.moveToNext()) {
						String RefNo = selectSOcancelHedDetDetails.getString(0);
						String TxnDate = selectSOcancelHedDetDetails
								.getString(1);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String ManuRef = selectSOcancelHedDetDetails
								.getString(2);
						String DelvDate = selectSOcancelHedDetDetails
								.getString(1);
						try {
							date = originalFormat.parse(DelvDate.replaceAll(
									"[-+/.^:,]", " "));
							DelvDate = targetFormat.format(date);

						} catch (ParseException ex) {
							DelvDate = "1900-01-01";
						}
						String DealCode = selectSOcancelHedDetDetails
								.getString(4);
						String RepCode = selectSOcancelHedDetDetails
								.getString(5);
						String AreaCode = selectSOcancelHedDetDetails
								.getString(6);
						String RouteCode = selectSOcancelHedDetDetails
								.getString(7);
						String DebCode = selectSOcancelHedDetDetails
								.getString(8);
						String LocCode = selectSOcancelHedDetDetails
								.getString(9);
						String Remarks = selectSOcancelHedDetDetails
								.getString(10);
						String CostCode = selectSOcancelHedDetDetails
								.getString(11);
						String CurCode = selectSOcancelHedDetDetails
								.getString(12);
						String CurRate = selectSOcancelHedDetDetails
								.getString(13);
						String TxnType = selectSOcancelHedDetDetails
								.getString(14);
						String InvAmt = selectSOcancelHedDetDetails
								.getString(15);
						String OutDis = selectSOcancelHedDetDetails
								.getString(16);
						String InvDis = selectSOcancelHedDetDetails
								.getString(17);
						String TotMkrAmt = selectSOcancelHedDetDetails
								.getString(18);
						String UnOvAmt = selectSOcancelHedDetDetails
								.getString(19);
						String TotalDis = selectSOcancelHedDetDetails
								.getString(20);
						String TotalAmt = selectSOcancelHedDetDetails
								.getString(21);
						String InvFlg = selectSOcancelHedDetDetails
								.getString(22);
						String SeqNo = selectSOcancelHedDetDetails
								.getString(23);
						String Itemcode = selectSOcancelHedDetDetails
								.getString(24);
						String Txnseqno = selectSOcancelHedDetDetails
								.getString(25);
						String SellPrice = selectSOcancelHedDetDetails
								.getString(26);
						String BSellPrice = selectSOcancelHedDetDetails
								.getString(27);
						String TSellPrice = selectSOcancelHedDetDetails
								.getString(28);
						String BTSellPrice = selectSOcancelHedDetDetails
								.getString(29);
						String CostPrice = selectSOcancelHedDetDetails
								.getString(30);
						String CaseQty = selectSOcancelHedDetDetails
								.getString(31);
						String PiceQty = selectSOcancelHedDetDetails
								.getString(32);
						String Type = selectSOcancelHedDetDetails.getString(33);
						String Qty = selectSOcancelHedDetDetails.getString(34);
						String BalQty = selectSOcancelHedDetDetails
								.getString(35);
						String DisPer = selectSOcancelHedDetDetails
								.getString(36);
						String DisAmt = selectSOcancelHedDetDetails
								.getString(37);
						String BDisAmt = selectSOcancelHedDetDetails
								.getString(38);
						String TaxAmt = selectSOcancelHedDetDetails
								.getString(39);
						String BTaxAmt = selectSOcancelHedDetDetails
								.getString(40);
						String Amt = selectSOcancelHedDetDetails.getString(41);
						String Bamt = selectSOcancelHedDetDetails.getString(42);
						String ReaCode = selectSOcancelHedDetDetails
								.getString(43);
						String AddUser = selectSOcancelHedDetDetails
								.getString(44);
						String ohAddDate = selectSOcancelHedDetDetails
								.getString(45);
						String AddMach = selectSOcancelHedDetDetails
								.getString(46);
						String prtcopy = selectSOcancelHedDetDetails
								.getString(47);
						String itemdisper = selectSOcancelHedDetDetails
								.getString(48);
						String itemdisperval = selectSOcancelHedDetDetails
								.getString(49);
						// Create values JSONArray
						JSONArray valuesarrayCanceledFOrdDet = new JSONArray();
						try {
							// Create values jsonObject
							JSONObject valuesarrayCancelSOhedDet = new JSONObject();
							valuesarrayCancelSOhedDet.put("RefNo", RefNo);
							valuesarrayCancelSOhedDet.put("TxnDate", TxnDate);
							valuesarrayCancelSOhedDet.put("ManuRef", ManuRef);
							valuesarrayCancelSOhedDet.put("DelvDate", DelvDate);
							valuesarrayCancelSOhedDet.put("DealCode", DealCode);
							valuesarrayCancelSOhedDet.put("RepCode", RepCode);
							valuesarrayCancelSOhedDet.put("AreaCode", AreaCode);
							valuesarrayCancelSOhedDet.put("RouteCode",
									RouteCode);
							valuesarrayCancelSOhedDet.put("DebCode", DebCode);
							valuesarrayCancelSOhedDet.put("LocCode", LocCode);
							valuesarrayCancelSOhedDet.put("Remarks", Remarks);
							valuesarrayCancelSOhedDet.put("CostCode", CostCode);
							valuesarrayCancelSOhedDet.put("CurCode", CurCode);
							valuesarrayCancelSOhedDet.put("CurRate", CurRate);
							valuesarrayCancelSOhedDet.put("TxnType", TxnType);
							valuesarrayCancelSOhedDet.put("InvAmt", InvAmt);
							valuesarrayCancelSOhedDet.put("OutDis", OutDis);
							valuesarrayCancelSOhedDet.put("InvDis", InvDis);
							valuesarrayCancelSOhedDet.put("TotMkrAmt",
									TotMkrAmt);
							valuesarrayCancelSOhedDet.put("UnOvAmt", UnOvAmt);
							valuesarrayCancelSOhedDet.put("TotalDis", TotalDis);
							valuesarrayCancelSOhedDet.put("TotalItmDis",
									TotalDis);
							valuesarrayCancelSOhedDet.put("TotalAmt", TotalAmt);
							valuesarrayCancelSOhedDet.put("InvFlg", InvFlg);
							valuesarrayCancelSOhedDet.put("SeqNo", SeqNo);
							valuesarrayCancelSOhedDet.put("Itemcode", Itemcode);
							valuesarrayCancelSOhedDet.put("Txnseqno", Txnseqno);
							valuesarrayCancelSOhedDet.put("SellPrice",
									SellPrice);
							valuesarrayCancelSOhedDet.put("BSellPrice",
									BSellPrice);
							valuesarrayCancelSOhedDet.put("TSellPrice",
									TSellPrice);
							valuesarrayCancelSOhedDet.put("BTSellPrice",
									BTSellPrice);
							valuesarrayCancelSOhedDet.put("CostPrice",
									CostPrice);
							valuesarrayCancelSOhedDet.put("CaseQty", CaseQty);
							valuesarrayCancelSOhedDet.put("PiceQty", PiceQty);
							valuesarrayCancelSOhedDet.put("Type", Type);
							valuesarrayCancelSOhedDet.put("Qty", Qty);
							valuesarrayCancelSOhedDet.put("BalQty", BalQty);
							valuesarrayCancelSOhedDet.put("DisPer", DisPer);
							valuesarrayCancelSOhedDet.put("DisAmt", DisAmt);
							valuesarrayCancelSOhedDet.put("BDisAmt", BDisAmt);
							valuesarrayCancelSOhedDet.put("TaxAmt", TaxAmt);
							valuesarrayCancelSOhedDet.put("BTaxAmt", BTaxAmt);
							valuesarrayCancelSOhedDet.put("Amt", Amt);
							valuesarrayCancelSOhedDet.put("BAmt", Bamt);
							valuesarrayCancelSOhedDet.put("ReaCode", ReaCode);
							valuesarrayCancelSOhedDet.put("AddUser", AddUser);
							valuesarrayCancelSOhedDet.put("AddDate", ohAddDate);
							valuesarrayCancelSOhedDet.put("AddMach", AddMach);
							valuesarrayCancelSOhedDet.put("prtcopy", prtcopy);
							valuesarrayCancelSOhedDet.put("DisPerAmt",
									itemdisper);
							valuesarrayCancelSOhedDet.put("DisValAmt",
									itemdisperval);
							valuesarrayCancelSOhedDet.put("RecordId", "1");
							valuesarrayCancelSOhedDet.put("DelDate", ohAddDate);
							valuesarrayCancelSOhedDet.put("DelType", "D");
							valuesarrayCancelSOhedDet.put("DelMach", AddMach);
							valuesarrayCancelSOhedDet.put("DelUser", AddUser);
							valuesarrayCancelSOhedDet.put("DelReasn", "");
							valuesarrayCancelSOhedDet.put("DbName",
									currentUserServerDB);
							valuesarrayCanceledFOrdDet
									.put(valuesarrayCancelSOhedDet
											.remove("[,]"));
							arCanceleOrdHedDet.add(valuesarrayCancelSOhedDet
									.toString());

						} catch (Exception e) {

						}

					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}
			}
			checkNetworkUploading();
			if (selectSOcancelHedDetDetails.getCount() <= 0) {
				Log.v(TAG, "ARRAY 4" + arCanceleOrdHedDet);
			} else {

				HttpPost requestlOrdDet = new HttpPost(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/insertlOrdDet");
				JSONStringer userJsonlOrdDet = null;
				try {
					userJsonlOrdDet = new JSONStringer().object().key("iDet")
							.value(arCanceleOrdHedDet);
				} catch (Exception e) {
				}

				StringEntity entitylOrdDet = null;
				try {
					// String repval = userJson.toString() + "}" + ",UTF-8";
					String formatLcso1 = userJsonlOrdDet.toString().replace(
							"\\", "");
					String formatLcso2 = formatLcso1.replace("\"[{", "[{");
					String formatLcso3 = formatLcso2.replace("}]\"", "}]}");

					Log.v(TAG, "****************************************\n");
					Log.v(TAG, "JSON1 =" + formatLcso3);
					entitylOrdDet = new StringEntity(formatLcso3, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				entitylOrdDet.setContentEncoding(new BasicHeader(
						HTTP.CONTENT_TYPE, "application/json"));
				entitylOrdDet.setContentType("application/json");
				requestlOrdDet.setEntity(entitylOrdDet);

				// Send request to WCF service
				DefaultHttpClient httpClientlOrdDet = new DefaultHttpClient();

				try {
					Log.e("response", "connect");
					HttpResponse responselOrdDet = httpClientlOrdDet
							.execute(requestlOrdDet);
					// Log.e("RES DJ1:", "RES DJ1:" +
					// responselOrdDet.toString());
					// ===========================================================
					HttpEntity entity_lOrdDet = responselOrdDet.getEntity();
					is = entity_lOrdDet.getContent();
					if (is != null) {

						try {
							BufferedReader reader_lOrdDet = new BufferedReader(
									new InputStreamReader(is, "iso-8859-1"), 8);
							sb = new StringBuilder();
							sb.append(reader_lOrdDet.readLine() + "\n");
							String line = "0";
							while ((line = reader_lOrdDet.readLine()) != null) {
								sb.append(line + "\n");
							}
							is.close();
							String result_lOrdDet = sb.toString();
							Log.e("RES DJ2:", "RESULT :" + result_lOrdDet);
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
				arCanceleOrdHedDet.clear();
			}
			// ****************Unloading Uploads
			// Handling*****************************8
			checkNetworkUploading();
			if (selectStockUnloadHeader != null) {
				if (selectStockUnloadHeader.getCount() > 0) {
					while (selectStockUnloadHeader.moveToNext()) {
						// FUnloadHedIndex =
						// selectStockUnloadHeader.getString(0);
						String RefNo = selectStockUnloadHeader.getString(1);
						String TxnDate = selectStockUnloadHeader.getString(2);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String ManuRef = selectStockUnloadHeader.getString(3);
						String CostCode = selectStockUnloadHeader.getString(4);
						String Remarks = selectStockUnloadHeader.getString(5);
						String TxnType = selectStockUnloadHeader.getString(6);
						String TotalAmt = selectStockUnloadHeader.getString(7);
						double TotalAmtdou = Double.parseDouble(TotalAmt
								.replaceAll("[,]", ""));
						double FTotalAmt = TotalAmtdou + 0.00;
						String PrintFTotalAmtStl = Double.toString(FTotalAmt);
						String DelPersn = selectStockUnloadHeader.getString(8);
						String DelAdd1 = selectStockUnloadHeader.getString(9);
						String DelAdd2 = selectStockUnloadHeader.getString(10);
						String DelAdd3 = selectStockUnloadHeader.getString(11);
						String VehicalNo = selectStockUnloadHeader
								.getString(12);
						String GlPost = selectStockUnloadHeader.getString(13);
						String GlBatch = selectStockUnloadHeader.getString(14);
						String AddUser = selectStockUnloadHeader.getString(15);
						String AddDatestlh = selectStockUnloadHeader
								.getString(16);
						String AddMach = selectStockUnloadHeader.getString(17);
						String TranFlg = selectStockUnloadHeader.getString(18);
						String ItemType = selectStockUnloadHeader.getString(19);
						String IntangFlg = selectStockUnloadHeader
								.getString(21);

						JSONArray valuesarrayfUnLoadhed = new JSONArray();
						try {
							// Create values jsonObject
							JSONObject valuesJsonfUnLoadhed = new JSONObject();
							valuesJsonfUnLoadhed.put("RefNo", RefNo);
							valuesJsonfUnLoadhed.put("TxnDate", TxnDate);
							valuesJsonfUnLoadhed.put("ManuRef", ManuRef);
							valuesJsonfUnLoadhed.put("DealCode", AgentDealCode);
							valuesJsonfUnLoadhed.put("CostCode", "000");
							valuesJsonfUnLoadhed.put("Remarks", Remarks);
							valuesJsonfUnLoadhed.put("TxnType", TxnType);
							valuesJsonfUnLoadhed.put("TotalAmt",
									PrintFTotalAmtStl);
							valuesJsonfUnLoadhed.put("DelPersn", DelPersn);
							valuesJsonfUnLoadhed.put("DelAdd1", DelAdd1);
							valuesJsonfUnLoadhed.put("DelAdd2", DelAdd2);
							valuesJsonfUnLoadhed.put("DelAdd3", DelAdd3);
							valuesJsonfUnLoadhed.put("VehicalNo", VehicalNo);
							valuesJsonfUnLoadhed.put("GlPost", GlPost);
							valuesJsonfUnLoadhed.put("GlBatch", GlBatch);
							valuesJsonfUnLoadhed.put("AddUser", AddUser);
							valuesJsonfUnLoadhed.put("AddDate", AddDatestlh);
							valuesJsonfUnLoadhed.put("AddMach", AddMach);
							valuesJsonfUnLoadhed.put("TranFlg", TranFlg);
							valuesJsonfUnLoadhed.put("ItemType", ItemType);
							valuesJsonfUnLoadhed.put("IntangFlg", IntangFlg);
							valuesJsonfUnLoadhed.put("DbName",
									currentUserServerDB);

							valuesarrayfUnLoadhed.put(valuesJsonfUnLoadhed
									.remove("[,]"));
							arfUnLoadhed.add(valuesJsonfUnLoadhed.toString());
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}
			}
			checkNetworkUploading();
			if (selectStockUnLoadDetails != null) {
				if (selectStockUnLoadDetails.getCount() > 0) {
					while (selectStockUnLoadDetails.moveToNext()) {
						// FStoUnloadDetIndex =
						// selectStockUnLoadDetails.getString(0);
						String RefNo = selectStockUnLoadDetails.getString(1);
						String TxnDate = selectStockUnLoadDetails.getString(2);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String LocCode = selectStockUnLoadDetails.getString(3);
						String TxnType = selectStockUnLoadDetails.getString(4);
						String SeqNo = selectStockUnLoadDetails.getString(5);
						String ItemCode = selectStockUnLoadDetails.getString(6);
						String CaseQty = selectStockUnLoadDetails.getString(7);
						String PiceQty = selectStockUnLoadDetails.getString(8);
						String Qty = selectStockUnLoadDetails.getString(9);
						String CostPrice = selectStockUnLoadDetails
								.getString(10);
						String Amt = selectStockUnLoadDetails.getString(11);
						String RecordChecked = selectStockUnLoadDetails
								.getString(13);
						String IntangFlg = selectStockUnLoadDetails
								.getString(18);

						JSONArray valuesarrayfUnLoadDet = new JSONArray();

						try {
							// Create values jsonObject
							JSONObject valuesJsonfUnLoadDet = new JSONObject();
							valuesJsonfUnLoadDet.put("RefNo", RefNo);
							valuesJsonfUnLoadDet.put("TxnDate", TxnDate);
							valuesJsonfUnLoadDet.put("LocCode", LocCode);
							valuesJsonfUnLoadDet.put("TxnType", TxnType);
							valuesJsonfUnLoadDet.put("SeqNo", SeqNo);
							valuesJsonfUnLoadDet.put("ItemCode", ItemCode);
							valuesJsonfUnLoadDet.put("CaseQty", CaseQty);
							valuesJsonfUnLoadDet.put("PiceQty",
									PiceQty.replaceAll("[,]", ""));
							valuesJsonfUnLoadDet.put("Qty",
									Qty.replaceAll("[,]", ""));
							valuesJsonfUnLoadDet.put("CostPrice",
									CostPrice.replaceAll("[,]", ""));
							valuesJsonfUnLoadDet.put("Amt",
									Amt.replaceAll("[,]", ""));
							valuesJsonfUnLoadDet.put("RecordChecked",
									RecordChecked);
							valuesJsonfUnLoadDet.put("IntangFlg", IntangFlg);
							valuesJsonfUnLoadDet.put("DbName",
									currentUserServerDB);
							valuesarrayfUnLoadDet.put(valuesJsonfUnLoadDet
									.remove("[,]"));
							arfUnLoadDet.add(valuesJsonfUnLoadDet.toString());
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}
			}
			checkNetworkUploading();
			String strFHUnload = arfUnLoadhed.toString();
			String strFDUnload = arfUnLoadDet.toString();

			if (selectStockUnloadHeader.getCount() <= 0) {
				Log.v(TAG, "ARRAY 5" + strFHUnload + "/" + strFDUnload);
			} else {

				strFHUnload = strFHUnload.replace("[", "");
				strFHUnload = strFHUnload.replace("]", "");
				strFDUnload = strFDUnload.replace("[", "");
				strFDUnload = strFDUnload.replace("]", "");
				// PDADBWebServiceM
				HttpPost requestfUnLoad = new HttpPost(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/insertfUnLoadhed");
				JSONStringer userJsonUnload = null;
				try {
					userJsonUnload = new JSONStringer().object().key("fULHed")
							.value(strFHUnload).key("fULDet")
							.value(strFDUnload);
				} catch (Exception e) {
				}

				StringEntity entityunload = null;
				try {
					// String repval = userJsonUnload.toString() + "}" +
					// ",UTF-8";
					String formatunload1 = userJsonUnload.toString().replace(
							"[", "");
					String formatunload2 = formatunload1.replace("]", "");
					String formatunload3 = formatunload2.replace("\\", "");

					String format4unload = "\"fULHed\":\"";
					String format5unloadunload = "\",\"fULDet\":\"";

					String format6unload = formatunload3.replace(format4unload,
							"\"fULHed\":[");
					String format7unload = format6unload.replace(
							format5unloadunload, "],\"fULDet\":[");
					format7unload = format7unload + "}";
					String djunload = format7unload.replace("\"}\"}", "\"}]}");

					Log.v(TAG, "****************************************\n");
					Log.v(TAG, "JSON1 =" + djunload);
					entityunload = new StringEntity(djunload, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				entityunload.setContentEncoding(new BasicHeader(
						HTTP.CONTENT_TYPE, "application/json"));
				entityunload.setContentType("application/json");
				requestfUnLoad.setEntity(entityunload);

				// Send requestfUnLoad to WCF service
				DefaultHttpClient httpClientunload = new DefaultHttpClient();

				try {
					Log.e("responseunload", "connect");
					HttpResponse responseunload = httpClientunload
							.execute(requestfUnLoad);
					// Log.e("RES DJ1:", "RES DJ1:" +
					// responseunload.toString());
					// ===========================================================
					HttpEntity entityunloade = responseunload.getEntity();
					is = entityunloade.getContent();
					if (is != null) {

						try {
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(is, "iso-8859-1"), 8);
							sb = new StringBuilder();
							sb.append(reader.readLine() + "\n");
							String line = "0";
							while ((line = reader.readLine()) != null) {
								sb.append(line + "\n");
							}
							is.close();
							String result = sb.toString();
							String result1 = result.replace("\"", "");

							if (result1.trim().equals("200")) {
								ContentValues unloadhedSynUpdateVal = new ContentValues();
								unloadhedSynUpdateVal.put("stlhedunSync", "1");
								mydb.update(STOCK_LOAD_HEADUN,
										unloadhedSynUpdateVal,
										"stlhedunSync ='0'", null);

								ContentValues unloaddetSynUpdateVal = new ContentValues();
								unloaddetSynUpdateVal.put("stldetunSync", "1");
								mydb.update(STOCK_LOAD_DETAILUN,
										unloaddetSynUpdateVal,
										"stldetunSync ='0'", null);

								String fInvOrdCountStr = Integer
										.toString(fOrdHedCount);
								SIupSummary = "(SO -" + fInvOrdCountStr + "/"
										+ fInvOrdCountStr + ")";
							}

							else {
								String result12 = result1.replace("\",", "");
								String result13 = result12.replace("\"", "");
								String result14 = result13.replace("\\", "");
								String result15 = result14.replace("200,", "");
								String[] items = result15.split(",");
								List<String> container = Arrays.asList(items);
								List<String> android = new ArrayList<String>(
										container);
								Log.e("RES DJ2:", "RESULT ELSE 200 :" + android);
								// Getting Iterator from List
								Iterator<String> iterator = android.iterator();
								Cursor selectStUnloadHeadDetailsReChk = null, selectStUnloadDetailsDataReChk = null;
								try {
									selectStUnloadHeadDetailsReChk = mydb
											.query(STOCK_LOAD_HEADUN, null,
													"stlhedunSync ='0'", null,
													null, null, null);
								} catch (Exception e) {
								}
								try {
									selectStUnloadDetailsDataReChk = mydb
											.query(STOCK_LOAD_DETAILUN, null,
													"stldetunSync ='0'", null,
													null, null, null);
								} catch (Exception e) {
								}
								while (iterator.hasNext()) {
									String ReadRefNumbers = iterator.next();
									Log.e("RES DJ2:", "UploadError REF:"
											+ ReadRefNumbers);
									if (selectStUnloadHeadDetailsReChk != null) {
										if (selectStUnloadHeadDetailsReChk
												.getCount() > 0) {
											while (selectStUnloadHeadDetailsReChk
													.moveToNext()) {
												String mainRefNoErrorHed = selectStUnloadHeadDetailsReChk
														.getString(1);
												ContentValues fstunloadhedSynUpdaterall = new ContentValues();
												fstunloadhedSynUpdaterall.put(
														"stlhedunSync", "7");
												mydb.update(
														STOCK_LOAD_HEADUN,
														fstunloadhedSynUpdaterall,
														"RefNo ='"
																+ mainRefNoErrorHed
																+ "'", null);
											}
										}
									}

									if (selectStUnloadDetailsDataReChk != null) {
										if (selectStUnloadDetailsDataReChk
												.getCount() > 0) {
											while (selectStUnloadDetailsDataReChk
													.moveToNext()) {
												String mainRefNoErrorDet = selectStUnloadDetailsDataReChk
														.getString(1);
												ContentValues fstunloaddetSynUpdaterall = new ContentValues();
												fstunloaddetSynUpdaterall.put(
														"stldetunSync", "7");
												mydb.update(
														STOCK_LOAD_DETAILUN,
														fstunloaddetSynUpdaterall,
														"RefNo ='"
																+ mainRefNoErrorDet
																+ "'", null);
											}
										}
									}
								}

								Cursor selectStUnloadHeadDetailsUpdate = null, selectStUnloadDetailsDataUpdate = null;
								try {
									selectStUnloadHeadDetailsUpdate = mydb
											.query(STOCK_LOAD_HEADUN, null,
													"stlhedunSync ='0'", null,
													null, null, null);
								} catch (Exception e) {
								}
								try {
									selectStUnloadDetailsDataUpdate = mydb
											.query(STOCK_LOAD_DETAILUN, null,
													"stldetunSync ='0'", null,
													null, null, null);
								} catch (Exception e) {
								}

								if (selectStUnloadHeadDetailsUpdate != null) {
									if (selectStUnloadHeadDetailsUpdate
											.getCount() > 0) {
										while (selectStUnloadHeadDetailsUpdate
												.moveToNext()) {
											String mainRefNoHed = selectStUnloadHeadDetailsUpdate
													.getString(1);
											ContentValues fstunloadhedSynUpdaterall = new ContentValues();
											fstunloadhedSynUpdaterall.put(
													"stlhedunSync", "1");
											mydb.update(STOCK_LOAD_HEADUN,
													fstunloadhedSynUpdaterall,
													"RefNo ='" + mainRefNoHed
															+ "'", null);
										}
									}
								}
								if (selectStUnloadDetailsDataUpdate != null) {
									if (selectStUnloadDetailsDataUpdate
											.getCount() > 0) {
										while (selectStUnloadDetailsDataUpdate
												.moveToNext()) {
											String mainRefNoDet = selectStUnloadDetailsDataUpdate
													.getString(1);
											ContentValues fstunloaddetSynUpdaterall = new ContentValues();
											fstunloaddetSynUpdaterall.put(
													"stldetunSync", "1");
											mydb.update(STOCK_LOAD_DETAILUN,
													fstunloaddetSynUpdaterall,
													"RefNo ='" + mainRefNoDet
															+ "'", null);
										}
									}
								}

								Cursor selectStUnloadHeadDetailsChkFail = null, selectStUnloadDetailsDataChkFail = null;
								try {
									selectStUnloadHeadDetailsChkFail = mydb
											.query(STOCK_LOAD_HEADUN, null,
													"stlhedunSync ='7'", null,
													null, null, null);
								} catch (Exception e) {
								}
								try {
									selectStUnloadDetailsDataChkFail = mydb
											.query(STOCK_LOAD_DETAILUN, null,
													"stldetunSync ='7'", null,
													null, null, null);
								} catch (Exception e) {
								}

								if (selectStUnloadHeadDetailsChkFail != null) {
									if (selectStUnloadHeadDetailsChkFail
											.getCount() > 0) {
										while (selectStUnloadHeadDetailsChkFail
												.moveToNext()) {
											String mainRefNoHedFail = selectStUnloadHeadDetailsChkFail
													.getString(1);
											ContentValues fstunloadhedSynUpdaterallFail = new ContentValues();
											fstunloadhedSynUpdaterallFail.put(
													"stlhedunSync", "0");
											mydb.update(
													STOCK_LOAD_HEADUN,
													fstunloadhedSynUpdaterallFail,
													"RefNo ='"
															+ mainRefNoHedFail
															+ "'", null);
										}
									}
								}
								if (selectStUnloadDetailsDataChkFail != null) {
									if (selectStUnloadDetailsDataChkFail
											.getCount() > 0) {
										while (selectStUnloadDetailsDataChkFail
												.moveToNext()) {
											String mainRefNoDetFail = selectStUnloadDetailsDataChkFail
													.getString(1);
											ContentValues fstunloaddetSynUpdaterallFail = new ContentValues();
											fstunloaddetSynUpdaterallFail.put(
													"stldetunSync", "0");
											mydb.update(
													STOCK_LOAD_DETAILUN,
													fstunloaddetSynUpdaterallFail,
													"RefNo ='"
															+ mainRefNoDetFail
															+ "'", null);
										}
									}
								}

							}
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				arfUnLoadhed.clear();
				arfUnLoadDet.clear();
			}

			// ******Uploading Invoice Receipt Details****
			checkNetworkUploading();
			if (selectReceiptHeadDetails != null) {
				if (selectReceiptHeadDetails.getCount() > 0) {
					while (selectReceiptHeadDetails.moveToNext()) {
						// FReceiptHedIndex =
						// selectReceiptHeadDetails.getString(0);
						String RefNo = selectReceiptHeadDetails.getString(1);
						String ManuRef = selectReceiptHeadDetails.getString(2);
						String SaleRefNo = selectReceiptHeadDetails
								.getString(3);
						String RepCode = selectReceiptHeadDetails.getString(4);
						String TxnType = selectReceiptHeadDetails.getString(5);
						String Chqno = selectReceiptHeadDetails.getString(6);
						String ChqDate = selectReceiptHeadDetails.getString(7);
						try {
							date = originalFormat.parse(ChqDate.replaceAll(
									"[-+/.^:,]", " "));
							ChqDate = targetFormat.format(date);

						} catch (ParseException ex) {
							ChqDate = "1900-01-01";
						}
						String TxnDate = selectReceiptHeadDetails.getString(8);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							// Log.v(TAG,"Old Format :"+
							// originalFormat.format(date));
							// Log.v(TAG,"New Format :" +
							// targetFormat.format(date));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String CurCode = selectReceiptHeadDetails.getString(9);
						String CurRate = selectReceiptHeadDetails.getString(10);
						String DebCode = selectReceiptHeadDetails.getString(11);
						String TotalAmt = selectReceiptHeadDetails
								.getString(12);
						String BTotalAmt = selectReceiptHeadDetails
								.getString(13);
						String BankCur = selectReceiptHeadDetails.getString(14);
						String BankRate = selectReceiptHeadDetails
								.getString(15);
						String BankAmt = selectReceiptHeadDetails.getString(16);
						String BankCharge = selectReceiptHeadDetails
								.getString(17);
						String BBankChg = selectReceiptHeadDetails
								.getString(18);
						String GnLsCal = selectReceiptHeadDetails.getString(19);
						String DbAcc = selectReceiptHeadDetails.getString(20);
						String PayType = selectReceiptHeadDetails.getString(21);
						String PrtCopy = selectReceiptHeadDetails.getString(22);
						String GlPost = selectReceiptHeadDetails.getString(23);
						String Remarks = selectReceiptHeadDetails.getString(24);
						String CardSlipNo = selectReceiptHeadDetails
								.getString(25);
						String ExpDate = selectReceiptHeadDetails.getString(26);
						try {
							date = originalFormat.parse(ExpDate.replaceAll(
									"[-+/.^:,]", " "));
							// Log.v(TAG,"Old Format :"+
							// originalFormat.format(date));
							// Log.v(TAG,"New Format :" +
							// targetFormat.format(date));
							ExpDate = targetFormat.format(date);
						} catch (ParseException ex) {
							ExpDate = "1900-01-01";
						}
						String CrdTypCode = selectReceiptHeadDetails
								.getString(27);
						String CCBankAmt = selectReceiptHeadDetails
								.getString(28);
						String GlBatch = selectReceiptHeadDetails.getString(29);
						String AddUser = selectReceiptHeadDetails.getString(30);
						String AddMach = selectReceiptHeadDetails.getString(31);
						String AddDate = selectReceiptHeadDetails.getString(32);
						try {
							date = originalFormat.parse(AddDate.replaceAll(
									"[-+/.^:,]", " "));
							// Log.v(TAG,"Old Format :"+
							// originalFormat.format(date));
							// Log.v(TAG,"New Format :" +
							// targetFormat.format(date));
							AddDate = targetFormat.format(date);
						} catch (ParseException ex) {
							AddDate = "1900-01-01";
						}

						JSONArray valuesarrayfDRecHed = new JSONArray();
						try {
							// Create values jsonObject
							JSONObject valuesJsonfDRecHed = new JSONObject();
							valuesJsonfDRecHed.put("RefNo", RefNo);
							valuesJsonfDRecHed.put("ManuRef", ManuRef);
							valuesJsonfDRecHed.put("SaleRefNo", SaleRefNo);
							valuesJsonfDRecHed.put("RepCode", RepCode);
							valuesJsonfDRecHed.put("TxnType", TxnType);
							valuesJsonfDRecHed.put("Chqno", Chqno);
							valuesJsonfDRecHed.put("ChqDate", ChqDate);
							valuesJsonfDRecHed.put("TxnDate", TxnDate);
							valuesJsonfDRecHed.put("CurCode", "LKR");
							valuesJsonfDRecHed.put("CurRate", CurRate);
							valuesJsonfDRecHed.put("DebCode", DebCode);
							valuesJsonfDRecHed.put("TotalAmt", "0.0");
							valuesJsonfDRecHed.put("BTotalAmt", "0.0");
							valuesJsonfDRecHed.put("BankCur", "LKR");
							valuesJsonfDRecHed.put("BankRate", BankRate);
							valuesJsonfDRecHed.put("BankAmt",
									BankAmt.replaceAll("[,]", ""));
							valuesJsonfDRecHed.put("BankCharge",
									BankCharge.replaceAll("[,]", ""));
							valuesJsonfDRecHed.put("BBankChg",
									BBankChg.replaceAll("[,]", ""));
							valuesJsonfDRecHed.put("GnLsCal", GnLsCal);
							valuesJsonfDRecHed.put("DbAcc", "00000001-000");
							valuesJsonfDRecHed.put("PayType", PayType);
							valuesJsonfDRecHed.put("PrtCopy", PrtCopy);
							valuesJsonfDRecHed.put("GlPost", GlPost);
							valuesJsonfDRecHed.put("Remarks", Remarks);
							valuesJsonfDRecHed.put("CardSlipNo", CardSlipNo);
							valuesJsonfDRecHed.put("ExpDate", ExpDate);
							valuesJsonfDRecHed.put("CrdTypCode", CrdTypCode);
							valuesJsonfDRecHed.put("CCBankAmt", CCBankAmt);
							valuesJsonfDRecHed.put("GlBatch", GlBatch);
							valuesJsonfDRecHed.put("AddUser", AddUser);
							valuesJsonfDRecHed.put("AddMach", AddMach);
							valuesJsonfDRecHed.put("AddDate", AddDate);
							valuesJsonfDRecHed.put("DbName",
									currentUserServerDB);

							valuesarrayfDRecHed.put(valuesJsonfDRecHed
									.remove("[,]"));
							arfDRecHed.add(valuesJsonfDRecHed.toString());
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}
			}
			checkNetworkUploading();
			if (selectInvReceiptDetails != null) {
				if (selectInvReceiptDetails.getCount() > 0) {
					while (selectInvReceiptDetails.moveToNext()) {

						// FReceiptDetIndex =
						// selectInvReceiptDetails.getString(0);
						String RefNo = selectInvReceiptDetails.getString(1);
						String RefNo1 = selectInvReceiptDetails.getString(2);
						String SaleRefNo = selectInvReceiptDetails.getString(3);
						String ManuRef = selectInvReceiptDetails.getString(4);
						String TxnType = selectInvReceiptDetails.getString(5);
						String TxnDate = selectInvReceiptDetails.getString(6);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String DtxnDate = selectInvReceiptDetails.getString(7);
						try {
							date = originalFormat.parse(DtxnDate.replaceAll(
									"[-+/.^:,]", " "));
							DtxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							DtxnDate = "1900-01-01";
						}
						String DtxnType = selectInvReceiptDetails.getString(8);
						String DCurCode = selectInvReceiptDetails.getString(9);
						String DCurRate = selectInvReceiptDetails.getString(10);
						String OCurRate = selectInvReceiptDetails.getString(11);
						String RepCode = selectInvReceiptDetails.getString(12);
						String Amt = selectInvReceiptDetails.getString(13);
						String BAmt = selectInvReceiptDetails.getString(14);
						String GainLosAmt = selectInvReceiptDetails
								.getString(15);
						String BnkChgs = selectInvReceiptDetails.getString(16);
						String BBnkChgs = selectInvReceiptDetails.getString(17);
						String AloAmt = selectInvReceiptDetails.getString(18);
						String OvPayAmt = selectInvReceiptDetails.getString(19);
						String OvPayBal = selectInvReceiptDetails.getString(20);

						JSONArray valuesarrayfDRecDet = new JSONArray();
						try {
							// Create values jsonObject
							JSONObject valuesJsonfDRecDet = new JSONObject();
							valuesJsonfDRecDet.put("RefNo", RefNo);
							valuesJsonfDRecDet.put("RefNo1", RefNo1);
							valuesJsonfDRecDet.put("SaleRefNo", SaleRefNo);
							valuesJsonfDRecDet.put("ManuRef", ManuRef);
							valuesJsonfDRecDet.put("TxnType", TxnType);
							valuesJsonfDRecDet.put("TxnDate", TxnDate);
							valuesJsonfDRecDet.put("DtxnDate", DtxnDate);
							valuesJsonfDRecDet.put("DtxnType", DtxnType);
							valuesJsonfDRecDet.put("DCurCode", "LKR");
							valuesJsonfDRecDet.put("DCurRate",
									DCurRate.replaceAll("[,]", ""));
							valuesJsonfDRecDet.put("OCurRate",
									OCurRate.replaceAll("[,]", ""));
							valuesJsonfDRecDet.put("RepCode", RepCode);
							valuesJsonfDRecDet.put("Amt",
									Amt.replaceAll("[,]", ""));
							valuesJsonfDRecDet.put("BAmt",
									BAmt.replaceAll("[,]", ""));
							valuesJsonfDRecDet.put("GainLosAmt",
									GainLosAmt.replaceAll("[,]", ""));
							valuesJsonfDRecDet.put("BnkChgs",
									BnkChgs.replaceAll("[,]", ""));
							valuesJsonfDRecDet.put("BBnkChgs",
									BBnkChgs.replaceAll("[,]", ""));
							valuesJsonfDRecDet.put("AloAmt",
									AloAmt.replaceAll("[,]", ""));
							valuesJsonfDRecDet.put("OvPayAmt",
									OvPayAmt.replaceAll("[,]", ""));
							valuesJsonfDRecDet.put("OvPayBal",
									OvPayBal.replaceAll("[,]", ""));
							valuesJsonfDRecDet.put("DbName",
									currentUserServerDB);

							valuesarrayfDRecDet.put(valuesJsonfDRecDet
									.remove("[,]"));
							arfDRecDet.add(valuesJsonfDRecDet.toString());

						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}
			}
			checkNetworkUploading();
			String strfDRecHed = arfDRecHed.toString();
			String strfDRecDet = arfDRecDet.toString();
			if (selectReceiptHeadDetails.getCount() <= 0) {
				Log.v(TAG, "ARRAY 6" + strfDRecHed + "/" + strfDRecDet);
			} else {

				strfDRecHed = strfDRecHed.replace("[", "");
				strfDRecHed = strfDRecHed.replace("]", "");
				strfDRecDet = strfDRecDet.replace("[", "");
				strfDRecDet = strfDRecDet.replace("]", "");
				// PDADBWebServiceM
				HttpPost requestfDRec = new HttpPost(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/insertfDRecHed");
				JSONStringer userJsonfDRec = null;
				try {
					userJsonfDRec = new JSONStringer().object().key("fDRHed")
							.value(strfDRecHed).key("fDRDet")
							.value(strfDRecDet);
				} catch (Exception e) {
				}

				StringEntity entityfDRec = null;
				try {
					// String repval = userJson.toString() + "}" + ",UTF-8";
					String formatfdr1 = userJsonfDRec.toString().replace("[",
							"");
					String formatfdr2 = formatfdr1.replace("]", "");
					String formatfdr3 = formatfdr2.replace("\\", "");

					String formatfdr4 = "\"fDRHed\":\"";
					String formatfdr5 = "\",\"fDRDet\":\"";

					String formatfdr6 = formatfdr3.replace(formatfdr4,
							"\"fDRHed\":[");
					String formatfdr7 = formatfdr6.replace(formatfdr5,
							"],\"fDRDet\":[");
					formatfdr7 = formatfdr7 + "}";
					String sendReqfDRec = formatfdr7.replace("\"}\"}", "\"}]}");

					// Log.v(TAG, "JSON1 =" + ddddd);
					Log.v(TAG, "****************************************\n");
					Log.v(TAG, "JSON1 =" + sendReqfDRec);
					entityfDRec = new StringEntity(sendReqfDRec, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				entityfDRec.setContentEncoding(new BasicHeader(
						HTTP.CONTENT_TYPE, "application/json"));
				entityfDRec.setContentType("application/json");
				requestfDRec.setEntity(entityfDRec);

				// Send request to WCF service
				DefaultHttpClient httpClientfDRec = new DefaultHttpClient();

				try {
					Log.e("response", "connect");
					HttpResponse responsefDRec = httpClientfDRec
							.execute(requestfDRec);
					HttpEntity entityfDRecEntity = responsefDRec.getEntity();
					is = entityfDRecEntity.getContent();
					if (is != null) {

						try {
							BufferedReader reader_fDRec = new BufferedReader(
									new InputStreamReader(is, "iso-8859-1"), 8);
							sb = new StringBuilder();
							sb.append(reader_fDRec.readLine() + "\n");
							String line = "0";
							while ((line = reader_fDRec.readLine()) != null) {
								sb.append(line + "\n");
							}
							is.close();
							String result_fDRec = sb.toString();
							String result_fDRec1 = result_fDRec.replace("\"",
									"");
							if (result_fDRec1.trim().equals("200")) {
								ContentValues receiptHedDetailsSynUpdateVal = new ContentValues();
								receiptHedDetailsSynUpdateVal.put(
										"recipthedSync", "1");
								mydb.update(RECEIPT_HEADER,
										receiptHedDetailsSynUpdateVal,
										"recipthedSync ='0'", null);

								ContentValues receiptDetDetailsSynUpdateVal = new ContentValues();
								receiptDetDetailsSynUpdateVal.put(
										"reciptdetSync", "1");
								mydb.update(RECEIPT_DETAILS,
										receiptDetDetailsSynUpdateVal,
										"reciptdetSync ='0'", null);
							}

							else {
								String result12 = result_fDRec1.replace("\",",
										"");
								String result13 = result12.replace("\"", "");
								String result14 = result13.replace("\\", "");
								String result15 = result14.replace("200,", "");
								String[] items = result14.split(",");
								List<String> container = Arrays.asList(items);
								List<String> android = new ArrayList<String>(
										container);
								Log.e("RES DJ2:", "RESULT ELSE 200 :" + android);
								// Getting Iterator from List
								Iterator<String> iterator = android.iterator();
								Cursor selectReceiptHeadDetailsReChk = null, selectReceiptDetailsDataReChk = null;
								try {
									selectReceiptHeadDetailsReChk = mydb.query(
											RECEIPT_HEADER, null,
											"recipthedSync ='0'", null, null,
											null, null);
								} catch (Exception e) {
								}
								try {
									selectReceiptDetailsDataReChk = mydb.query(
											RECEIPT_DETAILS, null,
											"reciptdetSync ='0'", null, null,
											null, null);
								} catch (Exception e) {
								}
								while (iterator.hasNext()) {
									String ReadRefNumbers = iterator.next();
									Log.e("RES DJ2:", "UploadError REF:"
											+ ReadRefNumbers);
									if (selectReceiptHeadDetailsReChk != null) {
										if (selectReceiptHeadDetailsReChk
												.getCount() > 0) {
											while (selectReceiptHeadDetailsReChk
													.moveToNext()) {
												String mainRefNoErrorHed = selectReceiptHeadDetailsReChk
														.getString(1);
												ContentValues fReceipthedSynUpdaterall = new ContentValues();
												fReceipthedSynUpdaterall.put(
														"recipthedSync", "7");
												mydb.update(
														RECEIPT_HEADER,
														fReceipthedSynUpdaterall,
														"RefNo ='"
																+ mainRefNoErrorHed
																+ "'", null);
											}
										}
									}

									if (selectReceiptDetailsDataReChk != null) {
										if (selectReceiptDetailsDataReChk
												.getCount() > 0) {
											while (selectReceiptDetailsDataReChk
													.moveToNext()) {
												String mainRefNoErrorDet = selectReceiptDetailsDataReChk
														.getString(1);
												ContentValues fReceiptdetSynUpdaterall = new ContentValues();
												fReceiptdetSynUpdaterall.put(
														"reciptdetSync", "7");
												mydb.update(
														RECEIPT_DETAILS,
														fReceiptdetSynUpdaterall,
														"RefNo ='"
																+ mainRefNoErrorDet
																+ "'", null);
											}
										}
									}
								}

								Cursor selectReceiptHeadDetailsUpdate = null, selectReceiptDetailsDataUpdate = null;
								try {
									selectReceiptHeadDetailsUpdate = mydb
											.query(RECEIPT_HEADER, null,
													"recipthedSync ='0'", null,
													null, null, null);
								} catch (Exception e) {
								}
								try {
									selectReceiptDetailsDataUpdate = mydb
											.query(RECEIPT_DETAILS, null,
													"reciptdetSync ='0'", null,
													null, null, null);
								} catch (Exception e) {
								}

								if (selectReceiptHeadDetailsUpdate != null) {
									if (selectReceiptHeadDetailsUpdate
											.getCount() > 0) {
										while (selectReceiptHeadDetailsUpdate
												.moveToNext()) {
											String mainRefNoHed = selectReceiptHeadDetailsUpdate
													.getString(1);
											ContentValues fReceipthedSynUpdaterall = new ContentValues();
											fReceipthedSynUpdaterall.put(
													"recipthedSync", "1");
											mydb.update(RECEIPT_HEADER,
													fReceipthedSynUpdaterall,
													"RefNo ='" + mainRefNoHed
															+ "'", null);
										}
									}
								}
								if (selectReceiptDetailsDataUpdate != null) {
									if (selectReceiptDetailsDataUpdate
											.getCount() > 0) {
										while (selectReceiptDetailsDataUpdate
												.moveToNext()) {
											String mainRefNoDet = selectReceiptDetailsDataUpdate
													.getString(1);
											ContentValues fReceiptdetSynUpdaterall = new ContentValues();
											fReceiptdetSynUpdaterall.put(
													"reciptdetSync", "1");
											mydb.update(RECEIPT_DETAILS,
													fReceiptdetSynUpdaterall,
													"RefNo ='" + mainRefNoDet
															+ "'", null);
										}
									}
								}

								Cursor selectReceiptHeadDetailsChkFail = null, selectReceiptDetailsDataChkFail = null;
								try {
									selectReceiptHeadDetailsChkFail = mydb
											.query(RECEIPT_HEADER, null,
													"recipthedSync ='7'", null,
													null, null, null);
								} catch (Exception e) {
								}
								try {
									selectReceiptDetailsDataChkFail = mydb
											.query(RECEIPT_DETAILS, null,
													"reciptdetSync ='7'", null,
													null, null, null);
								} catch (Exception e) {
								}

								if (selectReceiptHeadDetailsChkFail != null) {
									if (selectReceiptHeadDetailsChkFail
											.getCount() > 0) {
										while (selectReceiptHeadDetailsChkFail
												.moveToNext()) {
											String mainRefNoHedFail = selectReceiptHeadDetailsChkFail
													.getString(1);
											ContentValues fReceipthedSynUpdaterallFail = new ContentValues();
											fReceipthedSynUpdaterallFail.put(
													"recipthedSync", "0");
											mydb.update(
													RECEIPT_HEADER,
													fReceipthedSynUpdaterallFail,
													"RefNo ='"
															+ mainRefNoHedFail
															+ "'", null);
										}
									}
								}
								if (selectReceiptDetailsDataChkFail != null) {
									if (selectReceiptDetailsDataChkFail
											.getCount() > 0) {
										while (selectReceiptDetailsDataChkFail
												.moveToNext()) {
											String mainRefNoDetFail = selectReceiptDetailsDataChkFail
													.getString(1);
											ContentValues fReceiptdetSynUpdaterallFail = new ContentValues();
											fReceiptdetSynUpdaterallFail.put(
													"reciptdetSync", "0");
											mydb.update(
													RECEIPT_DETAILS,
													fReceiptdetSynUpdaterallFail,
													"RefNo ='"
															+ mainRefNoDetFail
															+ "'", null);
										}
									}
								}

							}

						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
				arfDRecHed.clear();
				arfDRecDet.clear();
			}
			// ****************************************************************
			checkNetworkUploading();
			if (selectStockfDamhed != null) {
				if (selectStockfDamhed.getCount() > 0) {
					while (selectStockfDamhed.moveToNext()) {
						// FUnloadHedIndex =
						// selectStockfDamhed.getString(0);
						String RefNo = selectStockfDamhed.getString(1);
						String TxnDate = selectStockfDamhed.getString(2);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String ManuRef = selectStockfDamhed.getString(3);
						String DealCode = selectStockfDamhed.getString(4);
						String Remarks = selectStockfDamhed.getString(5);
						String TxnType = selectStockfDamhed.getString(6);
						String TotalAmt = selectStockfDamhed.getString(7);
						String CostCode = selectStockfDamhed.getString(8);
						String ReaCode = selectStockfDamhed.getString(9);
						String GlPost = selectStockfDamhed.getString(10);
						String GlBatch = selectStockfDamhed.getString(11);
						String AddUser = selectStockfDamhed.getString(12);
						String AddDate = selectStockfDamhed.getString(13);
						String AddMach = selectStockfDamhed.getString(14);
						String ItemType = selectStockfDamhed.getString(15);

						JSONArray valuesarrayfDamhed = new JSONArray();
						try {
							// Create values jsonObject
							JSONObject valuesJsonfDamhed = new JSONObject();
							valuesJsonfDamhed.put("RefNo", RefNo);
							valuesJsonfDamhed.put("TxnDate", TxnDate);
							valuesJsonfDamhed.put("ManuRef", ManuRef);
							valuesJsonfDamhed.put("DealCode", AgentDealCode);
							valuesJsonfDamhed.put("Remarks", Remarks);
							valuesJsonfDamhed.put("TxnType", TxnType);
							valuesJsonfDamhed.put("TotalAmt",
									TotalAmt.replaceAll("[,]", ""));
							valuesJsonfDamhed.put("CostCode", "000");
							valuesJsonfDamhed.put("ReaCode", ReaCode);
							valuesJsonfDamhed.put("GlPost", GlPost);
							valuesJsonfDamhed.put("GlBatch", GlBatch);
							valuesJsonfDamhed.put("AddUser", AddUser);
							valuesJsonfDamhed.put("AddDate", AddDate);
							valuesJsonfDamhed.put("AddMach", AddMach);
							valuesJsonfDamhed.put("ItemType", ItemType);
							valuesJsonfDamhed
									.put("DbName", currentUserServerDB);

							valuesarrayfDamhed.put(valuesJsonfDamhed
									.remove("[,]"));
							arfDamHed.add(valuesJsonfDamhed.toString());
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}
			}
			checkNetworkUploading();
			if (selectStockfDamDet != null) {
				if (selectStockfDamDet.getCount() > 0) {
					while (selectStockfDamDet.moveToNext()) {
						// FDamageDetIndex = selectStockfDamDet.getString(0);
						String RefNo = selectStockfDamDet.getString(1);
						String TxnDate = selectStockfDamDet.getString(2);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String LocCode = selectStockfDamDet.getString(3);
						String TxnType = selectStockfDamDet.getString(4);
						String SeqNo = selectStockfDamDet.getString(5);
						String ItemCode = selectStockfDamDet.getString(6);
						String CaseQty = selectStockfDamDet.getString(7);
						String PiceQty = selectStockfDamDet.getString(8);
						String Qty = selectStockfDamDet.getString(9);
						String CostPrice = selectStockfDamDet.getString(10);
						String Amt = selectStockfDamDet.getString(11);
						String reaCode = selectStockfDamDet.getString(17);

						JSONArray valuesarrayfDamdet = new JSONArray();
						try {
							// Create values jsonObject
							JSONObject valuesJsonfDamdet = new JSONObject();
							valuesJsonfDamdet.put("RefNo", RefNo);
							valuesJsonfDamdet.put("TxnDate", TxnDate);
							valuesJsonfDamdet.put("LocCode", LocCode);
							valuesJsonfDamdet.put("TxnType", TxnType);
							valuesJsonfDamdet.put("SeqNo", SeqNo);
							valuesJsonfDamdet.put("ItemCode", ItemCode);
							valuesJsonfDamdet.put("CaseQty", CaseQty);
							valuesJsonfDamdet.put("PiceQty",
									PiceQty.replaceAll("[,]", ""));
							valuesJsonfDamdet.put("Qty", Qty);
							valuesJsonfDamdet.put("CostPrice",
									CostPrice.replaceAll("[,]", ""));
							valuesJsonfDamdet.put("Amt",
									Amt.replaceAll("[,]", ""));
							valuesJsonfDamdet.put("ReaCode", reaCode);
							valuesJsonfDamdet
									.put("DbName", currentUserServerDB);

							valuesarrayfDamdet.put(valuesJsonfDamdet
									.remove("[,]"));
							arfDamDet.add(valuesJsonfDamdet.toString());
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}
			}

			checkNetworkUploading();
			String strfDamHed = arfDamHed.toString();
			String strfDamDet = arfDamDet.toString();
			if (selectStockfDamhed.getCount() <= 0) {
				Log.v(TAG, "ARRAY 7" + strfDamHed + "/" + strfDamDet);
			} else {

				strfDamHed = strfDamHed.replace("[", "");
				strfDamHed = strfDamHed.replace("]", "");
				strfDamDet = strfDamDet.replace("[", "");
				strfDamDet = strfDamDet.replace("]", "");
				// PDADBWebServiceM
				HttpPost requestfDam = new HttpPost(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/insertfDamHed");
				JSONStringer userJsonfDam = null;
				try {
					userJsonfDam = new JSONStringer().object().key("fDhed")
							.value(strfDamHed).key("fDDet").value(strfDamDet);
				} catch (Exception e) {
				}

				StringEntity entityfDam = null;
				try {
					// String repval = userJson.toString() + "}" + ",UTF-8";
					String formatfdam1 = userJsonfDam.toString().replace("[",
							"");
					String formatfdam2 = formatfdam1.replace("]", "");
					String formatfdam3 = formatfdam2.replace("\\", "");

					String formatfdam4 = "\"fDhed\":\"";
					String formatfdam5 = "\",\"fDDet\":\"";

					String formatfdam6 = formatfdam3.replace(formatfdam4,
							"\"fDhed\":[");
					String formatfdam7 = formatfdam6.replace(formatfdam5,
							"],\"fDDet\":[");
					formatfdam7 = formatfdam7 + "}";
					String sendReqfDamage = formatfdam7.replace("\"}\"}",
							"\"}]}");
					Log.v(TAG, "****************************************\n");
					Log.v(TAG, "JSON1 =" + sendReqfDamage);
					entityfDam = new StringEntity(sendReqfDamage, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				entityfDam.setContentEncoding(new BasicHeader(
						HTTP.CONTENT_TYPE, "application/json"));
				entityfDam.setContentType("application/json");
				requestfDam.setEntity(entityfDam);

				// Send request to WCF service
				DefaultHttpClient httpClientfDamRec = new DefaultHttpClient();

				try {
					Log.e("response", "connect");
					HttpResponse responsefDamRec = httpClientfDamRec
							.execute(requestfDam);
					// Log.e("RES DJ1:", "RES DJ1:" +
					// responsefDamRec.toString());
					// ===========================================================
					HttpEntity entityfDamEntity = responsefDamRec.getEntity();
					is = entityfDamEntity.getContent();
					if (is != null) {

						try {
							BufferedReader reader_fDamRec = new BufferedReader(
									new InputStreamReader(is, "iso-8859-1"), 8);
							sb = new StringBuilder();
							sb.append(reader_fDamRec.readLine() + "\n");
							String line = "0";
							while ((line = reader_fDamRec.readLine()) != null) {
								sb.append(line + "\n");
							}
							is.close();
							String result_fDamRec = sb.toString();
							String result_fDamRec1 = result_fDamRec.replace(
									"\"", "");
							if (result_fDamRec1.trim().equals("200")) {
								ContentValues damageHedDetailsSynUpdateVal = new ContentValues();
								damageHedDetailsSynUpdateVal.put(
										"stldmhedSync", "1");
								mydb.update(STOCK_LOAD_HEADDAM,
										damageHedDetailsSynUpdateVal,
										"stldmhedSync ='0'", null);

								ContentValues damageDetDetailsSynUpdateVal = new ContentValues();
								damageDetDetailsSynUpdateVal.put(
										"stldmdetSync", "1");
								mydb.update(STOCK_LOAD_DETAILDAM,
										damageDetDetailsSynUpdateVal,
										"stldmdetSync ='0'", null);
							}

							else {
								String result12 = result_fDamRec1.replace(
										"\",", "");
								String result13 = result12.replace("\"", "");
								String result14 = result13.replace("\\", "");
								String result15 = result14.replace("200,", "");
								String[] items = result14.split(",");
								List<String> container = Arrays.asList(items);
								List<String> android = new ArrayList<String>(
										container);
								Log.e("RES DJ2:", "RESULT ELSE 200 :" + android);
								// Getting Iterator from List
								Iterator<String> iterator = android.iterator();
								Cursor selectDamageHeadDetailsReChk = null, selectDamageDetailsDataReChk = null;
								try {
									selectDamageHeadDetailsReChk = mydb.query(
											STOCK_LOAD_HEADDAM, null,
											"stldmhedSync ='0'", null, null,
											null, null);
								} catch (Exception e) {
								}
								try {
									selectDamageDetailsDataReChk = mydb.query(
											STOCK_LOAD_DETAILDAM, null,
											"stldmdetSync ='0'", null, null,
											null, null);
								} catch (Exception e) {
								}
								while (iterator.hasNext()) {
									String ReadRefNumbers = iterator.next();
									Log.e("RES DJ2:", "UploadError REF:"
											+ ReadRefNumbers);
									if (selectDamageHeadDetailsReChk != null) {
										if (selectDamageHeadDetailsReChk
												.getCount() > 0) {
											while (selectDamageHeadDetailsReChk
													.moveToNext()) {
												String mainRefNoErrorHed = selectDamageHeadDetailsReChk
														.getString(1);
												ContentValues fDamagehedSynUpdaterall = new ContentValues();
												fDamagehedSynUpdaterall.put(
														"stldmhedSync", "7");
												mydb.update(
														STOCK_LOAD_HEADDAM,
														fDamagehedSynUpdaterall,
														"RefNo ='"
																+ mainRefNoErrorHed
																+ "'", null);
											}
										}
									}

									if (selectDamageDetailsDataReChk != null) {
										if (selectDamageDetailsDataReChk
												.getCount() > 0) {
											while (selectDamageDetailsDataReChk
													.moveToNext()) {
												String mainRefNoErrorDet = selectDamageDetailsDataReChk
														.getString(1);
												ContentValues fDamagedetSynUpdaterall = new ContentValues();
												fDamagedetSynUpdaterall.put(
														"stldmdetSync", "7");
												mydb.update(
														STOCK_LOAD_DETAILDAM,
														fDamagedetSynUpdaterall,
														"RefNo ='"
																+ mainRefNoErrorDet
																+ "'", null);
											}
										}
									}
								}

								Cursor selectDamageHeadDetailsUpdate = null, selectDamageDetailsDataUpdate = null;
								try {
									selectDamageHeadDetailsUpdate = mydb.query(
											STOCK_LOAD_HEADDAM, null,
											"stldmhedSync ='0'", null, null,
											null, null);
								} catch (Exception e) {
								}
								try {
									selectDamageDetailsDataUpdate = mydb.query(
											STOCK_LOAD_DETAILDAM, null,
											"stldmdetSync ='0'", null, null,
											null, null);
								} catch (Exception e) {
								}

								if (selectDamageHeadDetailsUpdate != null) {
									if (selectDamageHeadDetailsUpdate
											.getCount() > 0) {
										while (selectDamageHeadDetailsUpdate
												.moveToNext()) {
											String mainRefNoHed = selectDamageHeadDetailsUpdate
													.getString(1);
											ContentValues fDamagehedSynUpdaterall = new ContentValues();
											fDamagehedSynUpdaterall.put(
													"stldmhedSync", "1");
											mydb.update(STOCK_LOAD_HEADDAM,
													fDamagehedSynUpdaterall,
													"RefNo ='" + mainRefNoHed
															+ "'", null);
										}
									}
								}
								if (selectDamageDetailsDataUpdate != null) {
									if (selectDamageDetailsDataUpdate
											.getCount() > 0) {
										while (selectDamageDetailsDataUpdate
												.moveToNext()) {
											String mainRefNoDet = selectDamageDetailsDataUpdate
													.getString(1);
											ContentValues fDamagedetSynUpdaterall = new ContentValues();
											fDamagedetSynUpdaterall.put(
													"stldmdetSync", "1");
											mydb.update(STOCK_LOAD_DETAILDAM,
													fDamagedetSynUpdaterall,
													"RefNo ='" + mainRefNoDet
															+ "'", null);
										}
									}
								}

								Cursor selectDamageHeadDetailsChkFail = null, selectDamageDetailsDataChkFail = null;
								try {
									selectDamageHeadDetailsChkFail = mydb
											.query(STOCK_LOAD_HEADDAM, null,
													"stldmhedSync ='7'", null,
													null, null, null);
								} catch (Exception e) {
								}
								try {
									selectDamageDetailsDataChkFail = mydb
											.query(STOCK_LOAD_DETAILDAM, null,
													"stldmdetSync ='7'", null,
													null, null, null);
								} catch (Exception e) {
								}

								if (selectDamageHeadDetailsChkFail != null) {
									if (selectDamageHeadDetailsChkFail
											.getCount() > 0) {
										while (selectDamageHeadDetailsChkFail
												.moveToNext()) {
											String mainRefNoHedFail = selectDamageHeadDetailsChkFail
													.getString(1);
											ContentValues fDamagehedSynUpdaterallFail = new ContentValues();
											fDamagehedSynUpdaterallFail.put(
													"stldmhedSync", "0");
											mydb.update(
													STOCK_LOAD_HEADDAM,
													fDamagehedSynUpdaterallFail,
													"RefNo ='"
															+ mainRefNoHedFail
															+ "'", null);
										}
									}
								}
								if (selectDamageDetailsDataChkFail != null) {
									if (selectDamageDetailsDataChkFail
											.getCount() > 0) {
										while (selectDamageDetailsDataChkFail
												.moveToNext()) {
											String mainRefNoDetFail = selectDamageDetailsDataChkFail
													.getString(1);
											ContentValues fDamagedetSynUpdaterallFail = new ContentValues();
											fDamagedetSynUpdaterallFail.put(
													"stldmdetSync", "0");
											mydb.update(
													STOCK_LOAD_DETAILDAM,
													fDamagedetSynUpdaterallFail,
													"RefNo ='"
															+ mainRefNoDetFail
															+ "'", null);
										}
									}
								}

							}

						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				arfDamHed.clear();
				arfDamDet.clear();
			}

			// =============================
			if (selectNonProCallDetails != null) {
				if (selectNonProCallDetails.getCount() > 0) {
					while (selectNonProCallDetails.moveToNext()) {

						String RefNo = selectNonProCallDetails.getString(1);
						String TxnDate = selectNonProCallDetails.getString(2);
						String DebCode = selectNonProCallDetails.getString(3);
						String DebName = selectNonProCallDetails.getString(4);
						String Status = selectNonProCallDetails.getString(5);
						String Reason = selectNonProCallDetails.getString(7);
						try {

							// DealerCode = currentUserTemp =
							// getAddDateTimeString() = deviceUser
							// Create values jsonObject
							JSONObject valuesJsonProductivehed = new JSONObject();

							valuesJsonProductivehed.put("RefNo", RefNo);
							try {
								date = originalFormat.parse(TxnDate.replaceAll(
										"[-+/.^:,]", " "));
								TxnDate = targetFormat.format(date);
							} catch (ParseException ex) {
								TxnDate = "1900-01-01";
							}
							valuesJsonProductivehed.put("TxnDate", TxnDate);
							valuesJsonProductivehed.put("DealCode", DealerCode);
							valuesJsonProductivehed.put("RepCode",
									currentUserTemp);
							valuesJsonProductivehed.put("Remarks", "Remarks");
							valuesJsonProductivehed.put("CostCode", "000");
							valuesJsonProductivehed.put("AddUser",
									currentUserTemp);
							valuesJsonProductivehed.put("AddDate",
									getAddDateTimeString().toString());
							valuesJsonProductivehed.put("AddMach", deviceUser);
							valuesJsonProductivehed.put("TranBatch", "00");
							valuesJsonProductivehed.put("DbName",
									currentUserServerDB);
							arNonProCallHed.add(valuesJsonProductivehed
									.toString());

							JSONObject valuesJsonProductiveDet = new JSONObject();
							valuesJsonProductiveDet.put("RefNo", RefNo);
							valuesJsonProductiveDet.put("TxnDate", TxnDate);
							valuesJsonProductiveDet.put("DebCode", DebCode);
							valuesJsonProductiveDet.put("Reason", Reason);
							valuesJsonProductiveDet.put("DbName",
									currentUserServerDB);
							arNonProCallDet.add(valuesJsonProductiveDet
									.toString());

						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					arrayLength = 1;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}
			}

			checkNetworkUploading();
			String strNonProCallHed = arNonProCallHed.toString();
			String strNonProCallDet = arNonProCallDet.toString();
			if (selectNonProCallDetails.getCount() <= 0) {
				Log.v(TAG, "ARRAY 7" + strNonProCallHed + "/"
						+ strNonProCallDet);
			} else {

				strNonProCallHed = strNonProCallHed.replace("[", "");
				strNonProCallHed = strNonProCallHed.replace("]", "");
				strNonProCallDet = strNonProCallDet.replace("[", "");
				strNonProCallDet = strNonProCallDet.replace("]", "");
				// PDADBWebServiceM
				HttpPost requestfDam = new HttpPost(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/insertFDaynPrdHed");
				JSONStringer userJsonfDam = null;
				try {
					userJsonfDam = new JSONStringer().object().key("fDHed")
							.value(strNonProCallHed).key("fDDet")
							.value(strNonProCallDet);
				} catch (Exception e) {
				}

				StringEntity entityfDam = null;
				try {
					// String repval = userJson.toString() + "}" + ",UTF-8";
					String formatfdam1 = userJsonfDam.toString().replace("[",
							"");
					String formatfdam2 = formatfdam1.replace("]", "");
					String formatfdam3 = formatfdam2.replace("\\", "");

					String formatfdam4 = "\"fDHed\":\"";
					String formatfdam5 = "\",\"fDDet\":\"";

					String formatfdam6 = formatfdam3.replace(formatfdam4,
							"\"fDHed\":[");
					String formatfdam7 = formatfdam6.replace(formatfdam5,
							"],\"fDDet\":[");
					formatfdam7 = formatfdam7 + "}";
					String sendReqfDamage = formatfdam7.replace("\"}\"}",
							"\"}]}");
					Log.v(TAG, "****************************************\n");
					Log.v(TAG, "JSON1 =" + sendReqfDamage);
					entityfDam = new StringEntity(sendReqfDamage, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				entityfDam.setContentEncoding(new BasicHeader(
						HTTP.CONTENT_TYPE, "application/json"));
				entityfDam.setContentType("application/json");
				requestfDam.setEntity(entityfDam);

				// Send request to WCF service
				DefaultHttpClient httpClientfDamRec = new DefaultHttpClient();

				try {
					Log.e("response", "connect");
					HttpResponse responsefDamRec = httpClientfDamRec
							.execute(requestfDam);
					// Log.e("RES DJ1:", "RES DJ1:" +
					// responsefDamRec.toString());
					// ===========================================================
					HttpEntity entityfDamEntity = responsefDamRec.getEntity();
					is = entityfDamEntity.getContent();
					if (is != null) {

						try {
							BufferedReader reader_fDamRec = new BufferedReader(
									new InputStreamReader(is, "iso-8859-1"), 8);
							sb = new StringBuilder();
							sb.append(reader_fDamRec.readLine() + "\n");
							String line = "0";
							while ((line = reader_fDamRec.readLine()) != null) {
								sb.append(line + "\n");
							}
							is.close();
							String result_fDamRec = sb.toString();
							String result_fDamRec1 = result_fDamRec.replace(
									"\"", "");
							Log.e("response", "connect:" + result_fDamRec1);
							if (result_fDamRec1.trim().equals("200")) {
								ContentValues damageHedDetailsSynUpdateVal = new ContentValues();
								damageHedDetailsSynUpdateVal.put(
										"stldmhedSync", "1");
								mydb.update(DAILY_NONE_PRDCALLS_HEAD,
										damageHedDetailsSynUpdateVal,
										"stldmhedSync ='0'", null);
							}

							else {

							}

						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				arNonProCallHed.clear();
				arNonProCallDet.clear();
			}
			/********** Uploading GPS *******/

			checkNetworkUploading();
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			try {
				String query = "SELECT _id,device_time,longitude,latitude,emi_number FROM fRepGps Where sync_state ='0' LIMIT 10";
				salesRegGps = mydb.rawQuery(query, null);
			} catch (Exception e) {
			}

			if (salesRegGps != null) {
				if (salesRegGps.getCount() > 0) {
					while (salesRegGps.moveToNext()) {
						gps_record_id = salesRegGps.getString(0);
						gps_device_time = salesRegGps.getString(1);
						gps_latitude = salesRegGps.getString(2);
						gps_longitude = salesRegGps.getString(3);
						gps_emi_number = salesRegGps.getString(4);

						// Create values JSONArray
						JSONArray valuesarrayFinvHed = new JSONArray();
						try {
							// Create values jsonObject
							JSONObject valuesJsonFinvHed = new JSONObject();
							valuesJsonFinvHed.put("longitude", gps_longitude);
							valuesJsonFinvHed.put("latitude", gps_latitude);
							valuesJsonFinvHed.put("eminumber", gps_emi_number);
							valuesJsonFinvHed.put("repcode", currentUserTemp);
							valuesJsonFinvHed.put("invnumber", "0000");
							valuesJsonFinvHed.put("gpsdatetime", gps_device_time);
							valuesJsonFinvHed.put("DbName", currentUserServerDB);
							arRepGpsRecords.add(valuesJsonFinvHed.toString()
									.trim());

						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}

					if (salesRegGps.getCount() <= 0) {
					} else {
						String strFH = arRepGpsRecords.toString().trim();
						Log.e("json", "json created :" + strFH);
						HttpPost request = new HttpPost(
								connectionURL
										+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/insertfRepGps");
						JSONStringer userJson = null;
						try {
							userJson = new JSONStringer().object().key("fGps")
									.value(strFH);
						} catch (Exception e) {
						}
						StringEntity entity = null;
						try {
							String format1 = userJson.toString();
							format1 = format1.replace("\\", "");
							format1 = format1.replace("\"[{", "[{");
							format1 = format1.replace("}]\"", "}]}");

							Log.v(TAG, "JSON - Request: =" + format1);
							entity = new StringEntity(format1, "UTF-8");
						} catch (Exception e) {
						}

						entity.setContentEncoding(new BasicHeader(
								HTTP.CONTENT_TYPE, "application/json"));
						entity.setContentType("application/json");
						request.setEntity(entity);
						// Send request to WCF service
						DefaultHttpClient httpClient = new DefaultHttpClient();
						try {
							Log.e("response", "connect");
							HttpResponse response = httpClient.execute(request);
							// ===========================================================
							HttpEntity entitye = response.getEntity();
							is = entitye.getContent();
							if (is != null) {

								try {
									BufferedReader reader = new BufferedReader(
											new InputStreamReader(is,
													"iso-8859-1"), 8);
									sb = new StringBuilder();
									sb.append(reader.readLine() + "\n");
									String line = "0";
									while ((line = reader.readLine()) != null) {
										sb.append(line + "\n");
									}
									is.close();
									String result = sb.toString();
									Log.e("String Responce ",
											"Print Responce 100 :" + result);
								} catch (Exception e1) {
									e1.printStackTrace();
								}
							}
							// ==================================
							Log.e("response",
									"response get 200 :" + response.toString());
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(response.getEntity()
											.getContent(), "UTF-8"));
							String json = reader.readLine();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
			SynchDetails.dismiss();
			checkNetworkUploading();

			Cursor getRecordNotUpFInvHed = null;
			// *******Secondry Invoice********
			try {
				getRecordNotUpFInvHed = mydb.query(INV_HEADER, null,
						"invhedSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}
			if (getRecordNotUpFInvHed != null) {
				if (getRecordNotUpFInvHed.getCount() > 0) {
					while (getRecordNotUpFInvHed.moveToNext()) {
						int fInvHedNotUpCount = getRecordNotUpFInvHed
								.getCount();
						String uploadingInvoice = Integer
								.toString(fInvHedCount);
						String uploadingFailInvoice = Integer
								.toString(fInvHedNotUpCount);
						SIupSummary = "SI :" + "(" + uploadingFailInvoice + "/"
								+ uploadingInvoice + ")";
					}
				}
			}

			Cursor getRecordNotUpFordHed = null;
			try {
				getRecordNotUpFordHed = mydb.query(STOCK_ORDER_HEAD, null,
						"stordhedSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}
			if (getRecordNotUpFordHed != null) {
				if (getRecordNotUpFordHed.getCount() > 0) {
					while (getRecordNotUpFordHed.moveToNext()) {
						int fOrdHedNotUpCount = getRecordNotUpFordHed
								.getCount();
						String uploadingSOInvoice = Integer
								.toString(fOrdHedCount);
						String uploadingFailSOInvoice = Integer
								.toString(fOrdHedNotUpCount);
						SOupSummary = "SO :" + "(" + uploadingFailSOInvoice
								+ "/" + uploadingSOInvoice + ")";
					}
				}
			}

			if (SIupSummary == null && SOupSummary == null) {
				SIupSummary = "(SI - 0/0)";
				SOupSummary = "(SO - 0/0)";
			} else if (SIupSummary == null && SOupSummary != null) {
				SIupSummary = "(SI - 0/0)";
			} else if (SIupSummary != null && SOupSummary == null) {
				SOupSummary = "(SO - 0/0)";
			}

			if (networkFailRec == 99) {
				UploadAlertMessageUploading = SIupSummary
						+ " / "
						+ SOupSummary
						+ "Uploading Data Completed.\n Within Uploading Network Error Occurred. Please Upload Again To Verify Data...";
			} else {
				UploadAlertMessageUploading = SIupSummary + " / " + SOupSummary
						+ "Uploading Data Completed..";
			}

			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_InvoiceMenu.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("UPLOAD STATUS");
			// Setting Dialog Message
			alertDialog.setMessage(UploadAlertMessageUploading);
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					fInvHedCount = 0;
					fOrdHedCount = 0;
					fInvHedCountFail = 0;
					fOrdHedCountFail = 0;
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;

		}
	}

	// *****Uploading data using old web services******
	private class ReUploadingInvoiceData extends AsyncTask<Void, Void, Void> {
		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(DM_InvoiceMenu.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Uploading");
			// Set progressdialog message
			mProgressDialog.setMessage("Uploading Invoice Details...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			Cursor selectFcompanyBranch = null;
			Cursor selectInvHeadDetails = null;
			Cursor selectStockLoadHeader = null;
			Cursor selectStockUnloadHeader = null;
			Cursor selectReceiptHeadDetails = null;
			Cursor selectDamageHeader = null;
			Cursor selectAdjustmentHeader = null;
			Cursor selectOrderHeader = null;
			// company branch
			try {
				selectFcompanyBranch = mydb.query(INV_COMPANY_BRANCH, null,
						null, null, null, null, null);
			} catch (Exception e) {
			}
			// invoice header
			try {
				selectInvHeadDetails = mydb.query(INV_HEADER, null,
						"invhedSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}
			// stock load header
			try {
				selectStockLoadHeader = mydb.query(STOCK_LOAD_HEAD, null,
						"stlhedSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}
			// Unloading header
			try {
				selectStockUnloadHeader = mydb.query(STOCK_LOAD_HEADUN, null,
						"stlhedunSync = '0'", null, null, null, null);
			} catch (Exception e) {
			}
			// Receipt Header Uploading

			try {
				selectReceiptHeadDetails = mydb.query(RECEIPT_HEADER, null,
						"recipthedSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}
			// Damage Transfer
			try {
				selectDamageHeader = mydb.query(STOCK_LOAD_HEADDAM, null,
						"stldmhedSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}

			// Stock adjustment , deduction header
			try {
				selectAdjustmentHeader = mydb.query(ADJUST_ADDITION_HEADER,
						null, "adjHedSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}

			// Sales order header
			try {
				selectOrderHeader = mydb.query(STOCK_ORDER_HEAD, null,
						"stordhedSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}

			// ******Upload fCompanyBranch**************
			if (selectFcompanyBranch != null) {
				if (selectFcompanyBranch.getCount() > 0) {
					checkNetworkUploading();
					while (selectFcompanyBranch.moveToNext()) {

						String BranchCode = selectFcompanyBranch.getString(1);
						String RecordId = selectFcompanyBranch.getString(2);
						String cSettingsCode = selectFcompanyBranch
								.getString(3);
						String nNumVal = selectFcompanyBranch.getString(4);
						HttpPost request = new HttpPost(
								connectionURL
										+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/InUpdatefCompanyBranch");

						JSONStringer userJson = null;

						try {

							userJson = new JSONStringer().object()
									.key("fCBInUp").object().key("BranchCode")
									.value(BranchCode).key("cSettingsCode")
									.value(cSettingsCode).key("nNumVal")
									.value(nNumVal).key("DbName")
									.value(currentUserServerDB).endObject();
							// .key("RecordId").value("10")
							Log.e("json", "json created");
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						StringEntity entity = null;
						try {
							entity = new StringEntity(userJson.toString(),
									"UTF-8");
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						entity.setContentEncoding(new BasicHeader(
								HTTP.CONTENT_TYPE, "application/json"));
						entity.setContentType("application/json");

						request.setEntity(entity);

						// Send request to WCF service
						DefaultHttpClient httpClient = new DefaultHttpClient();

						try {
							Log.e("response", "connect");
							HttpResponse response = httpClient.execute(request);
							// ===========================================================
							HttpEntity entitye = response.getEntity();
							is = entity.getContent();
							if (is != null) {

								try {
									BufferedReader reader = new BufferedReader(
											new InputStreamReader(is,
													"iso-8859-1"), 8);
									sb = new StringBuilder();
									sb.append(reader.readLine() + "\n");
									String line = "0";
									while ((line = reader.readLine()) != null) {
										sb.append(line + "\n");
									}
									is.close();
									String result = sb.toString();
									Log.e("String Responce", "Print Responce:"
											+ result);
								} catch (Exception e1) {
									e1.printStackTrace();
								}
							}
							// ==================================
							Log.e("response",
									"response get:" + response.toString());
							// System.out.println(response.toString());
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(response.getEntity()
											.getContent(), "UTF-8"));
							String json = reader.readLine();
							Log.e("json string", "test " + json.toString()
									+ " lazim");
							System.out.println(json);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}

			}
			// ******Upload FInvHed**************
			if (selectInvHeadDetails != null) {
				if (selectInvHeadDetails.getCount() > 0) {
					while (selectInvHeadDetails.moveToNext()) {

						FInvHedIndex = selectInvHeadDetails.getString(0);
						String RefNo = selectInvHeadDetails.getString(1);
						String RefNo1 = selectInvHeadDetails.getString(2);
						String InvType = selectInvHeadDetails.getString(3);
						String TxnDate = selectInvHeadDetails.getString(4);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							Log.v(TAG,
									"Old Format :"
											+ originalFormat.format(date));
							Log.v(TAG,
									"New Format :" + targetFormat.format(date));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String ManuRef = selectInvHeadDetails.getString(5);
						String DealCode = selectInvHeadDetails.getString(6);
						String RepCode = selectInvHeadDetails.getString(7);
						String AreaCode = selectInvHeadDetails.getString(8);
						String RouteCode = selectInvHeadDetails.getString(9);
						String DebCode = selectInvHeadDetails.getString(10);
						String LocCode = selectInvHeadDetails.getString(11);
						String Remarks = selectInvHeadDetails.getString(12);
						String CostCode = selectInvHeadDetails.getString(13);
						String CurCode = selectInvHeadDetails.getString(14);
						String CurRate = selectInvHeadDetails.getString(15);
						String TxnType = selectInvHeadDetails.getString(16);
						String InvAmt = selectInvHeadDetails.getString(17);
						String OutDis = selectInvHeadDetails.getString(18);
						// Invoice Discount Value
						String InvDis = selectInvHeadDetails.getString(19);
						double InvDisVal = Double.parseDouble(InvDis
								.replaceAll("[,]", ""));

						String TotMkrAmt = selectInvHeadDetails.getString(20);
						String UnOvAmt = selectInvHeadDetails.getString(21);
						// Total Discount
						String TotalDis = selectInvHeadDetails.getString(22);
						double TotalDisVal = Double.parseDouble(TotalDis
								.replaceAll("[,]", ""));

						String TotalAmt = selectInvHeadDetails.getString(23);
						double TotalAmtdou = Double.parseDouble(TotalAmt
								.replaceAll("[,]", ""));
						double FTotalAmt = TotalAmtdou + 0.00;
						String PrintFTotalAmt = Double.toString(FTotalAmt);
						String AddUser = selectInvHeadDetails.getString(24);
						String AddDate = selectInvHeadDetails.getString(25);
						/*
						 * try { date = originalFormat.parse(AddDate.replaceAll(
						 * "[-+/.^:,]", " ")); Log.v(TAG, "Old Format :" +
						 * originalFormat.format(date)); Log.v(TAG,
						 * "New Format :" + targetFormat.format(date)); AddDate
						 * = targetFormat.format(date);
						 * 
						 * } catch (ParseException ex) { AddDate = "1900-01-01";
						 * }
						 */
						String AddMach = selectInvHeadDetails.getString(26);
						String prtcopy = selectInvHeadDetails.getString(27);
						String TranBatch = selectInvHeadDetails.getString(30);
						// Header Discount
						String outDisVal = selectInvHeadDetails.getString(33);
						double outDisValue = Double.parseDouble(outDisVal
								.replaceAll("[,]", ""));

						// Line Items Discount
						double LineItemsDis = TotalDisVal
								- (InvDisVal + outDisValue);
						String LineItemsDisString = Double
								.toString(LineItemsDis);

						// Upload record
						HttpPost request = new HttpPost(
								connectionURL
										+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/insertFInvHed");

						JSONStringer userJson = null;

						try {
							count = count + 1;
							Log.e("json", "Count:" + count);
							userJson = new JSONStringer()
									.object()
									.key("fHed")
									.object()
									.key("RefNo")
									.value(RefNo)
									.key("RefNo1")
									.value(RefNo1)
									.key("InvType")
									.value(InvType)
									.key("TxnDate")
									.value(TxnDate)
									.key("ManuRef")
									.value(ManuRef)
									.key("DealCode")
									.value(DealCode)
									.key("RepCode")
									.value(RepCode)
									.key("AreaCode")
									.value(AreaCode)
									.key("RouteCode")
									.value(RouteCode)
									.key("DebCode")
									.value(DebCode)
									.key("LocCode")
									.value(LocCode)
									.key("Remarks")
									.value(Remarks)
									.key("CostCode")
									.value(CostCode)
									.key("CurCode")
									.value(CurCode)
									.key("CurRate")
									.value(CurRate)
									.key("TxnType")
									.value(TxnType)
									.key("InvAmt")
									.value(InvAmt)
									.key("OutDis")
									.value(OutDis)
									.key("InvDis")
									.value(InvDis)
									.key("TotMkrAmt")
									.value(TotMkrAmt.replaceAll("[,]", ""))
									.key("UnOvAmt")
									.value(UnOvAmt.replaceAll("[,]", ""))
									.key("TotalDis")
									.value(TotalDis.replaceAll("[,]", ""))
									.key("TotalItmDis")
									.value(LineItemsDisString.replaceAll("[,]",
											""))
									.key("TotalAmt")
									.value(PrintFTotalAmt.replaceAll("[,]", ""))
									.key("AddUser").value(AddUser)
									.key("AddDate").value(AddDate)
									.key("AddMach").value(AddMach)
									.key("prtcopy").value(prtcopy)
									.key("outDisVal").value(outDisVal)
									.key("TranBatch").value(" ").key("DbName")
									.value(currentUserServerDB).endObject();
							Log.e("json", "json created");
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						StringEntity entity = null;
						try {
							entity = new StringEntity(userJson.toString(),
									"UTF-8");
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						entity.setContentEncoding(new BasicHeader(
								HTTP.CONTENT_TYPE, "application/json"));
						entity.setContentType("application/json");

						request.setEntity(entity);

						// Send request to WCF service
						DefaultHttpClient httpClient = new DefaultHttpClient();

						try {
							Log.e("response", "connect");
							HttpResponse response = httpClient.execute(request);

							// ===========================================================
							HttpEntity entitye = response.getEntity();
							is = entity.getContent();
							if (is != null) {

								try {
									BufferedReader reader = new BufferedReader(
											new InputStreamReader(is,
													"iso-8859-1"), 8);
									sb = new StringBuilder();
									sb.append(reader.readLine() + "\n");
									String line = "0";
									while ((line = reader.readLine()) != null) {
										sb.append(line + "\n");
									}
									is.close();
									String result = sb.toString();
									Log.e("String Responce", "Print Responce:"
											+ result);
								} catch (Exception e1) {
									e1.printStackTrace();
								}
							}
							// ==================================
							Log.e(" ", "Res:" + response.toString());
							// System.out.println(response.toString());
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(response.getEntity()
											.getContent(), "UTF-8"));
							String json = reader.readLine();
							String CheckStateDet = json.toString().replaceAll(
									"[\'\"]", "");
							if (CheckStateDet.equals("200")) {
								Log.v(TAG, "STOCK_LOAD_DETAIL**:"
										+ CheckStateDet);
								ContentValues changeSyncStatefLoadDet = new ContentValues();
								changeSyncStatefLoadDet.put("invhedSync", "1");
								mydb.update(INV_HEADER,
										changeSyncStatefLoadDet,
										"invhead_id ='" + FInvHedIndex + "'",
										null);
							}
							Log.e("json string", "test " + json.toString()
									+ " lazim");
							System.out.println(json);
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}

			}
			// ******Upload fLoadhed**************
			if (selectStockLoadHeader != null) {
				if (selectStockLoadHeader.getCount() > 0) {
					while (selectStockLoadHeader.moveToNext()) {
						LoadingHeaderIndex = selectStockLoadHeader.getString(0);
						String RefNo = selectStockLoadHeader.getString(1);
						String TxnDate = selectStockLoadHeader.getString(2);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							Log.v(TAG,
									"Old Format :"
											+ originalFormat.format(date));
							Log.v(TAG,
									"New Format :" + targetFormat.format(date));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String ManuRef = selectStockLoadHeader.getString(3);
						String CostCode = selectStockLoadHeader.getString(4);
						String Remarks = selectStockLoadHeader.getString(5);
						String TxnType = selectStockLoadHeader.getString(6);
						String TotalAmt = selectStockLoadHeader.getString(7);
						double TotalAmtdou = Double.parseDouble(TotalAmt
								.replaceAll("[,]", ""));
						double FTotalAmt = TotalAmtdou + 0.00;
						String PrintFTotalAmtStl = Double.toString(FTotalAmt);

						String DelPersn = selectStockLoadHeader.getString(8);
						String DelAdd1 = selectStockLoadHeader.getString(9);
						String DelAdd2 = selectStockLoadHeader.getString(10);
						String DelAdd3 = selectStockLoadHeader.getString(11);
						String VehicalNo = selectStockLoadHeader.getString(12);
						String GlPost = selectStockLoadHeader.getString(13);
						String GlBatch = selectStockLoadHeader.getString(14);
						String AddUser = selectStockLoadHeader.getString(15);
						String AddDatestlh = selectStockLoadHeader
								.getString(16);
						/*
						 * try { date =
						 * originalFormat.parse(AddDatestlh.replaceAll(
						 * "[-+/.^:,]", " ")); Log.v(TAG, "Old Format :" +
						 * originalFormat.format(date)); Log.v(TAG,
						 * "New Format :" + targetFormat.format(date));
						 * AddDatestlh = targetFormat.format(date);
						 * 
						 * } catch (ParseException ex) { AddDatestlh =
						 * "1900-01-01"; }
						 */
						String AddMach = selectStockLoadHeader.getString(17);
						String TranFlg = selectStockLoadHeader.getString(18);
						String ItemType = selectStockLoadHeader.getString(19);

						HttpPost request = new HttpPost(
								connectionURL
										+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/insertfLoadhed");

						JSONStringer userJson = null;

						try {

							userJson = new JSONStringer().object().key("fLHed")
									.object().key("RefNo").value(RefNo)
									.key("TxnDate").value(TxnDate)
									.key("ManuRef").value(ManuRef)
									.key("DealCode").value(AgentDealCode)
									.key("CostCode").value("000")
									.key("Remarks").value(Remarks)
									.key("TxnType").value(TxnType)
									.key("TotalAmt").value(PrintFTotalAmtStl)
									.key("DelPersn").value(DelPersn)
									.key("DelAdd1").value(DelAdd1)
									.key("DelAdd2").value(DelAdd2)
									.key("DelAdd3").value(DelAdd3)
									.key("VehicalNo").value(VehicalNo)
									.key("GlPost").value(GlPost).key("GlBatch")
									.value(GlBatch).key("AddUser")
									.value(AddUser).key("AddDate")
									.value(AddDatestlh).key("AddMach")
									.value(AddMach).key("TranFlg")
									.value(TranFlg).key("ItemType")
									.value(ItemType).key("DbName")
									.value(currentUserServerDB).endObject();
							// .key("RecordId").value("10")
							Log.e("json", "json created");
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						StringEntity entity = null;
						try {
							entity = new StringEntity(userJson.toString(),
									"UTF-8");
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						entity.setContentEncoding(new BasicHeader(
								HTTP.CONTENT_TYPE, "application/json"));
						entity.setContentType("application/json");

						request.setEntity(entity);

						// Send request to WCF service
						DefaultHttpClient httpClient = new DefaultHttpClient();

						try {
							Log.e("response", "connect");
							HttpResponse response = httpClient.execute(request);
							// ===========================================================
							HttpEntity entitye = response.getEntity();
							is = entity.getContent();
							if (is != null) {

								try {
									BufferedReader reader = new BufferedReader(
											new InputStreamReader(is,
													"iso-8859-1"), 8);
									sb = new StringBuilder();
									sb.append(reader.readLine() + "\n");
									String line = "0";
									while ((line = reader.readLine()) != null) {
										sb.append(line + "\n");
									}
									is.close();
									String result = sb.toString();
									Log.e("String Responce", "Print Responce:"
											+ result);
								} catch (Exception e1) {
									e1.printStackTrace();
								}
							}
							// ==================================
							Log.e("response",
									"response get:" + response.toString());
							// System.out.println(response.toString());
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(response.getEntity()
											.getContent(), "UTF-8"));
							String json = reader.readLine();
							String CheckStateHed = json.toString().replaceAll(
									"[\'\"]", "");
							if (CheckStateHed.equals("200")) {
								Log.v(TAG, "STOCK_LOAD_HEAD**:" + CheckStateHed);
								ContentValues changeSyncStatefLoadhed = new ContentValues();
								changeSyncStatefLoadhed.put("stlhedSync", "1");
								mydb.update(STOCK_LOAD_HEAD,
										changeSyncStatefLoadhed, "RecordId ='"
												+ LoadingHeaderIndex + "'",
										null);
							}

							Log.e("json string", "test " + json.toString()
									+ " lazim");
							System.out.println(json);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}

			}
			// ******Upload fUnLoadhed**************
			if (selectStockUnloadHeader != null) {
				if (selectStockUnloadHeader.getCount() > 0) {
					while (selectStockUnloadHeader.moveToNext()) {
						FUnloadHedIndex = selectStockUnloadHeader.getString(0);
						String RefNo = selectStockUnloadHeader.getString(1);
						String TxnDate = selectStockUnloadHeader.getString(2);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							Log.v(TAG,
									"Old Format :"
											+ originalFormat.format(date));
							Log.v(TAG,
									"New Format :" + targetFormat.format(date));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String ManuRef = selectStockUnloadHeader.getString(3);
						String CostCode = selectStockUnloadHeader.getString(4);
						String Remarks = selectStockUnloadHeader.getString(5);
						String TxnType = selectStockUnloadHeader.getString(6);
						String TotalAmt = selectStockUnloadHeader.getString(7);
						double TotalAmtdou = Double.parseDouble(TotalAmt
								.replaceAll("[,]", ""));
						double FTotalAmt = TotalAmtdou + 0.00;
						String PrintFTotalAmtStl = Double.toString(FTotalAmt);

						String DelPersn = selectStockUnloadHeader.getString(8);
						String DelAdd1 = selectStockUnloadHeader.getString(9);
						String DelAdd2 = selectStockUnloadHeader.getString(10);
						String DelAdd3 = selectStockUnloadHeader.getString(11);
						String VehicalNo = selectStockUnloadHeader
								.getString(12);
						String GlPost = selectStockUnloadHeader.getString(13);
						String GlBatch = selectStockUnloadHeader.getString(14);
						String AddUser = selectStockUnloadHeader.getString(15);
						String AddDatestlh = selectStockUnloadHeader
								.getString(16);
						/*
						 * try { date =
						 * originalFormat.parse(AddDatestlh.replaceAll(
						 * "[-+/.^:,]", " ")); Log.v(TAG, "Old Format :" +
						 * originalFormat.format(date)); Log.v(TAG,
						 * "New Format :" + targetFormat.format(date));
						 * AddDatestlh = targetFormat.format(date);
						 * 
						 * } catch (ParseException ex) { AddDatestlh =
						 * "1900-01-01"; }
						 */
						String AddMach = selectStockUnloadHeader.getString(17);
						String TranFlg = selectStockUnloadHeader.getString(18);
						String ItemType = selectStockUnloadHeader.getString(19);
						String IntangFlg = selectStockUnloadHeader
								.getString(21);

						HttpPost request = new HttpPost(
								connectionURL
										+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/insertfUnLoadhed");

						JSONStringer userJson = null;
						try {
							userJson = new JSONStringer().object()
									.key("fULHed").object().key("RefNo")
									.value(RefNo).key("TxnDate").value(TxnDate)
									.key("ManuRef").value(ManuRef)
									.key("DealCode").value(AgentDealCode)
									.key("CostCode").value("000")
									.key("Remarks").value(Remarks)
									.key("TxnType").value(TxnType)
									.key("TotalAmt").value(PrintFTotalAmtStl)
									.key("DelPersn").value(DelPersn)
									.key("DelAdd1").value(DelAdd1)
									.key("DelAdd2").value(DelAdd2)
									.key("DelAdd3").value(DelAdd3)
									.key("VehicalNo").value(VehicalNo)
									.key("GlPost").value(GlPost).key("GlBatch")
									.value(GlBatch).key("AddUser")
									.value(AddUser).key("AddDate")
									.value(AddDatestlh).key("AddMach")
									.value(AddMach).key("TranFlg")
									.value(TranFlg).key("ItemType")
									.value(ItemType).key("IntangFlg")
									.value(IntangFlg).key("DbName")
									.value(currentUserServerDB).endObject();
							// .key("RecordId").value("10")
							Log.e("json", "json created");
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						StringEntity entity = null;
						try {
							entity = new StringEntity(userJson.toString(),
									"UTF-8");
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						entity.setContentEncoding(new BasicHeader(
								HTTP.CONTENT_TYPE, "application/json"));
						entity.setContentType("application/json");

						request.setEntity(entity);

						// Send request to WCF service
						DefaultHttpClient httpClient = new DefaultHttpClient();

						try {
							Log.e("response", "connect");
							HttpResponse response = httpClient.execute(request);
							// ===========================================================
							HttpEntity entitye = response.getEntity();
							is = entity.getContent();
							if (is != null) {

								try {
									BufferedReader reader = new BufferedReader(
											new InputStreamReader(is,
													"iso-8859-1"), 8);
									sb = new StringBuilder();
									sb.append(reader.readLine() + "\n");
									String line = "0";
									while ((line = reader.readLine()) != null) {
										sb.append(line + "\n");
									}
									is.close();
									String result = sb.toString();
									Log.e("String Responce", "Print Responce:"
											+ result);
								} catch (Exception e1) {
									e1.printStackTrace();
								}
							}
							// ==================================
							Log.e("response",
									"response get:" + response.toString());
							// System.out.println(response.toString());
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(response.getEntity()
											.getContent(), "UTF-8"));
							String json = reader.readLine();
							String CheckStateDet = json.toString().replaceAll(
									"[\'\"]", "");
							if (CheckStateDet.equals("200")) {
								Log.v(TAG, "STOCK_LOAD_HEADUN**:"
										+ CheckStateDet);
								ContentValues changeSyncStatefLoadDet = new ContentValues();
								changeSyncStatefLoadDet
										.put("stlhedunSync", "1");
								mydb.update(STOCK_LOAD_HEADUN,
										changeSyncStatefLoadDet, "RecordId ='"
												+ FUnloadHedIndex + "'", null);
							}
							Log.e("json string", "test " + json.toString()
									+ " lazim");
							System.out.println(json);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}

			}
			// ******Upload fDRecHed**************
			if (selectReceiptHeadDetails != null) {
				if (selectReceiptHeadDetails.getCount() > 0) {
					while (selectReceiptHeadDetails.moveToNext()) {
						FReceiptHedIndex = selectReceiptHeadDetails
								.getString(0);
						String RefNo = selectReceiptHeadDetails.getString(1);
						String ManuRef = selectReceiptHeadDetails.getString(2);
						String SaleRefNo = selectReceiptHeadDetails
								.getString(3);
						String RepCode = selectReceiptHeadDetails.getString(4);
						String TxnType = selectReceiptHeadDetails.getString(5);
						String Chqno = selectReceiptHeadDetails.getString(6);
						String ChqDate = selectReceiptHeadDetails.getString(7);
						try {
							date = originalFormat.parse(ChqDate.replaceAll(
									"[-+/.^:,]", " "));
							Log.v(TAG,
									"Old Format :"
											+ originalFormat.format(date));
							Log.v(TAG,
									"New Format :" + targetFormat.format(date));
							ChqDate = targetFormat.format(date);

						} catch (ParseException ex) {
							ChqDate = "1900-01-01";
						}
						String TxnDate = selectReceiptHeadDetails.getString(8);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							Log.v(TAG,
									"Old Format :"
											+ originalFormat.format(date));
							Log.v(TAG,
									"New Format :" + targetFormat.format(date));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String CurCode = selectReceiptHeadDetails.getString(9);
						String CurRate = selectReceiptHeadDetails.getString(10);
						String DebCode = selectReceiptHeadDetails.getString(11);
						String TotalAmt = selectReceiptHeadDetails
								.getString(12);
						String BTotalAmt = selectReceiptHeadDetails
								.getString(13);
						String BankCur = selectReceiptHeadDetails.getString(14);
						String BankRate = selectReceiptHeadDetails
								.getString(15);
						String BankAmt = selectReceiptHeadDetails.getString(16);
						String BankCharge = selectReceiptHeadDetails
								.getString(17);
						String BBankChg = selectReceiptHeadDetails
								.getString(18);
						String GnLsCal = selectReceiptHeadDetails.getString(19);
						String DbAcc = selectReceiptHeadDetails.getString(20);
						String PayType = selectReceiptHeadDetails.getString(21);
						String PrtCopy = selectReceiptHeadDetails.getString(22);
						String GlPost = selectReceiptHeadDetails.getString(23);
						String Remarks = selectReceiptHeadDetails.getString(24);
						String CardSlipNo = selectReceiptHeadDetails
								.getString(25);
						String ExpDate = selectReceiptHeadDetails.getString(26);
						try {
							date = originalFormat.parse(ExpDate.replaceAll(
									"[-+/.^:,]", " "));
							Log.v(TAG,
									"Old Format :"
											+ originalFormat.format(date));
							Log.v(TAG,
									"New Format :" + targetFormat.format(date));
							ExpDate = targetFormat.format(date);

						} catch (ParseException ex) {
							ExpDate = "1900-01-01";
						}
						String CrdTypCode = selectReceiptHeadDetails
								.getString(27);
						String CCBankAmt = selectReceiptHeadDetails
								.getString(28);
						String GlBatch = selectReceiptHeadDetails.getString(29);
						String AddUser = selectReceiptHeadDetails.getString(30);
						String AddMach = selectReceiptHeadDetails.getString(31);
						String AddDate = selectReceiptHeadDetails.getString(32);
						try {
							date = originalFormat.parse(AddDate.replaceAll(
									"[-+/.^:,]", " "));
							Log.v(TAG,
									"Old Format :"
											+ originalFormat.format(date));
							Log.v(TAG,
									"New Format :" + targetFormat.format(date));
							AddDate = targetFormat.format(date);

						} catch (ParseException ex) {
							AddDate = "1900-01-01";
						}
						// Upload record
						HttpPost request = new HttpPost(
								connectionURL
										+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/insertfDRecHed");

						JSONStringer userJson = null;

						try {
							count = count + 1;
							Log.e("json", "Count:" + count);
							userJson = new JSONStringer().object()
									.key("fDRHed").object().key("RefNo")
									.value(RefNo).key("ManuRef").value(ManuRef)
									.key("SaleRefNo").value(SaleRefNo)
									.key("RepCode").value(RepCode)
									.key("TxnType").value(TxnType).key("Chqno")
									.value(Chqno).key("ChqDate").value(ChqDate)
									.key("TxnDate").value(TxnDate)
									.key("CurCode").value(CurCode)
									.key("CurRate").value(CurRate)
									.key("DebCode").value(DebCode)
									.key("TotalAmt").value("0.0")
									.key("BTotalAmt").value("0.0")
									.key("BankCur").value(BankCur)
									.key("BankRate").value(BankRate)
									.key("BankAmt")
									.value(BankAmt.replaceAll("[,]", ""))
									.key("BankCharge")
									.value(BankCharge.replaceAll("[,]", ""))
									.key("BBankChg")
									.value(BBankChg.replaceAll("[,]", ""))
									.key("GnLsCal").value(GnLsCal).key("DbAcc")
									.value(DbAcc.replaceAll("[,]", ""))
									.key("PayType").value(PayType)
									.key("PrtCopy").value(PrtCopy)
									.key("GlPost").value(GlPost).key("Remarks")
									.value(Remarks).key("CardSlipNo")
									.value(CardSlipNo).key("ExpDate")
									.value(ExpDate).key("CrdTypCode")
									.value(CrdTypCode).key("CCBankAmt")
									.value(CCBankAmt.replaceAll("[,]", ""))
									.key("GlBatch").value(GlBatch)
									.key("AddUser").value(AddUser)
									.key("AddMach").value(AddMach)
									.key("AddDate").value(AddDate)
									.key("DbName").value(currentUserServerDB)
									.endObject();
							Log.e("json", "json created");
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						StringEntity entity = null;
						try {
							entity = new StringEntity(userJson.toString(),
									"UTF-8");
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						entity.setContentEncoding(new BasicHeader(
								HTTP.CONTENT_TYPE, "application/json"));
						entity.setContentType("application/json");

						request.setEntity(entity);

						// Send request to WCF service
						DefaultHttpClient httpClient = new DefaultHttpClient();

						try {
							Log.e("response", "connect");
							HttpResponse response = httpClient.execute(request);

							// ===========================================================
							HttpEntity entitye = response.getEntity();
							is = entity.getContent();
							if (is != null) {

								try {
									BufferedReader reader = new BufferedReader(
											new InputStreamReader(is,
													"iso-8859-1"), 8);
									sb = new StringBuilder();
									sb.append(reader.readLine() + "\n");
									String line = "0";
									while ((line = reader.readLine()) != null) {
										sb.append(line + "\n");
									}
									is.close();
									String result = sb.toString();
									Log.e("String Responce", "Print Responce:"
											+ result);
								} catch (Exception e1) {
									e1.printStackTrace();
								}
							}
							// ==================================
							Log.e(" ", "Res:" + response.toString());
							// System.out.println(response.toString());
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(response.getEntity()
											.getContent(), "UTF-8"));
							String json = reader.readLine();
							String CheckStateDet = json.toString().replaceAll(
									"[\'\"]", "");
							if (CheckStateDet.equals("200")) {
								Log.v(TAG, "RECEIPT_HEADER**:" + CheckStateDet);
								ContentValues changeSyncStatefLoadDet = new ContentValues();
								changeSyncStatefLoadDet.put("recipthedSync",
										"1");
								mydb.update(RECEIPT_HEADER,
										changeSyncStatefLoadDet, "reched_id ='"
												+ FReceiptHedIndex + "'", null);
							}
							Log.e("json string", "test " + json.toString()
									+ " lazim");
							System.out.println(json);
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}

			}
			// ******Upload fDamhed**************selectDamageHeader
			if (selectDamageHeader != null) {
				if (selectDamageHeader.getCount() > 0) {
					while (selectDamageHeader.moveToNext()) {

						FStlDamHedIndex = selectDamageHeader.getString(0);
						String RefNo = selectDamageHeader.getString(1);
						String TxnDate = selectDamageHeader.getString(2);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String ManuRef = selectDamageHeader.getString(3);
						String DealCode = selectDamageHeader.getString(4);
						String Remarks = selectDamageHeader.getString(5);
						String TxnType = selectDamageHeader.getString(6);
						String TotalAmt = selectDamageHeader.getString(7);
						String CostCode = selectDamageHeader.getString(8);
						String ReaCode = selectDamageHeader.getString(9);
						String GlPost = selectDamageHeader.getString(10);
						String GlBatch = selectDamageHeader.getString(11);
						String AddUser = selectDamageHeader.getString(12);
						String AddDate = selectDamageHeader.getString(13);
						/*
						 * try { date = originalFormat.parse(AddDate.replaceAll(
						 * "[-+/.^:,]", " ")); Log.v(TAG, "Old Format :" +
						 * originalFormat.format(date)); Log.v(TAG,
						 * "New Format :" + targetFormat.format(date)); AddDate
						 * = targetFormat.format(date);
						 * 
						 * } catch (ParseException ex) { AddDate = "1900-01-01";
						 * }
						 */
						String AddMach = selectDamageHeader.getString(14);
						String ItemType = selectDamageHeader.getString(15);

						// Upload record
						HttpPost request = new HttpPost(
								connectionURL
										+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/insertfDamHed");

						JSONStringer userJson = null;

						try {
							count = count + 1;
							Log.e("json", "Count:" + count);
							userJson = new JSONStringer().object().key("fDhed")
									.object().key("RefNo").value(RefNo)
									.key("TxnDate").value(TxnDate)
									.key("ManuRef").value(ManuRef)
									.key("DealCode").value(AgentDealCode)
									.key("Remarks").value(Remarks)
									.key("TxnType").value(TxnType)
									.key("TotalAmt")
									.value(TotalAmt.replaceAll("[,]", ""))
									.key("CostCode").value("000")
									.key("ReaCode").value(ReaCode)
									.key("GlPost").value(GlPost).key("GlBatch")
									.value(GlBatch).key("AddUser")
									.value(AddUser).key("AddDate")
									.value(AddDate).key("AddMach")
									.value(AddMach).key("ItemType")
									.value(ItemType).key("DbName")
									.value(currentUserServerDB).endObject();
							Log.e("json", "json created");
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						StringEntity entity = null;
						try {
							entity = new StringEntity(userJson.toString(),
									"UTF-8");
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						entity.setContentEncoding(new BasicHeader(
								HTTP.CONTENT_TYPE, "application/json"));
						entity.setContentType("application/json");

						request.setEntity(entity);

						// Send request to WCF service
						DefaultHttpClient httpClient = new DefaultHttpClient();

						try {
							Log.e("response", "connect");
							HttpResponse response = httpClient.execute(request);

							// ===========================================================
							HttpEntity entitye = response.getEntity();
							is = entity.getContent();
							if (is != null) {

								try {
									BufferedReader reader = new BufferedReader(
											new InputStreamReader(is,
													"iso-8859-1"), 8);
									sb = new StringBuilder();
									sb.append(reader.readLine() + "\n");
									String line = "0";
									while ((line = reader.readLine()) != null) {
										sb.append(line + "\n");
									}
									is.close();
									String result = sb.toString();
									Log.e("String Responce", "Print Responce:"
											+ result);
								} catch (Exception e1) {
									e1.printStackTrace();
								}
							}
							// ==================================
							Log.e(" ", "Res:" + response.toString());
							// System.out.println(response.toString());
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(response.getEntity()
											.getContent(), "UTF-8"));
							String json = reader.readLine();
							String CheckStateDet = json.toString().replaceAll(
									"[\'\"]", "");
							if (CheckStateDet.equals("200")) {
								Log.v(TAG, "STOCK_LOAD_HEADDAM**:"
										+ CheckStateDet);
								ContentValues changeSyncStatefLoadDet = new ContentValues();
								changeSyncStatefLoadDet
										.put("stldmhedSync", "1");
								mydb.update(STOCK_LOAD_HEADDAM,
										changeSyncStatefLoadDet, "RecordId ='"
												+ FStlDamHedIndex + "'", null);
							}
							Log.e("json string", "test " + json.toString()
									+ " lazim");
							System.out.println(json);
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}

			}

			/*
			 * // ******Upload fAdjhed************** if (selectAdjustmentHeader
			 * != null) { if (selectAdjustmentHeader.getCount() > 0) { while
			 * (selectAdjustmentHeader.moveToNext()) { FAdjAdditionHedIndex =
			 * selectAdjustmentHeader .getString(0); String RefNo =
			 * selectAdjustmentHeader.getString(1); String TxnDate =
			 * selectAdjustmentHeader.getString(2); try { date =
			 * originalFormat.parse(TxnDate.replaceAll( "[-+/.^:,]", " "));
			 * TxnDate = targetFormat.format(date);
			 * 
			 * } catch (ParseException ex) { TxnDate = "1900-01-01"; } String
			 * CostCode = selectAdjustmentHeader.getString(3); String ManuRef =
			 * selectAdjustmentHeader.getString(4); String DealCode =
			 * selectAdjustmentHeader.getString(5); String RefNo2 =
			 * selectAdjustmentHeader.getString(6); String TxnType =
			 * selectAdjustmentHeader.getString(7); String TotalAmt =
			 * selectAdjustmentHeader.getString(8); String Remarks =
			 * selectAdjustmentHeader.getString(9); String LocCode =
			 * selectAdjustmentHeader.getString(10); String ReaCode =
			 * selectAdjustmentHeader.getString(11); String GlPost =
			 * selectAdjustmentHeader.getString(12); String GlBatch =
			 * selectAdjustmentHeader.getString(13); String AddUser =
			 * selectAdjustmentHeader.getString(14); String AddDate =
			 * selectAdjustmentHeader.getString(15);
			 * 
			 * try { date = originalFormat.parse(AddDate.replaceAll(
			 * "[-+/.^:,]", " ")); AddDate = targetFormat.format(date);
			 * 
			 * } catch (ParseException ex) { AddDate = "1900-01-01"; }
			 * 
			 * String AddMach = selectAdjustmentHeader.getString(16); String
			 * ItemType = selectAdjustmentHeader.getString(17); HttpPost request
			 * = new HttpPost( connectionURL +
			 * "/PDADBWebServiceN/PDADBWebServiceRest.svc/insertfAdjhed");
			 * 
			 * JSONStringer userJson = null; try { userJson = new
			 * JSONStringer().object() .key("fadhed").object().key("RefNo")
			 * .value(RefNo).key("TxnDate").value(TxnDate)
			 * .key("CostCode").value(CostCode) .key("ManuRef").value(ManuRef)
			 * .key("DealCode").value(AgentDealCode)
			 * .key("RefNo2").value(RefNo2).key("TxnType")
			 * .value(TxnType).key("TotalAmt") .value(TotalAmt.replaceAll("[,]",
			 * "")) .key("Remarks").value(Remarks)
			 * .key("LocCode").value(LocCode) .key("ReaCode").value(ReaCode)
			 * .key("GlPost").value(GlPost).key("GlBatch")
			 * .value(GlBatch).key("AddUser") .value(AddUser).key("AddDate")
			 * .value(AddDate).key("AddMach") .value(AddMach).key("ItemType")
			 * .value(ItemType).key("DbName")
			 * .value(currentUserServerDB).endObject(); //
			 * .key("RecordId").value("10") Log.e("json", "json created"); }
			 * catch (JSONException e) {
			 * 
			 * // TODO Auto-generated catch block e.printStackTrace(); }
			 * 
			 * StringEntity entity = null; try { entity = new
			 * StringEntity(userJson.toString(), "UTF-8"); } catch
			 * (UnsupportedEncodingException e) { // TODO Auto-generated catch
			 * block e.printStackTrace(); } entity.setContentEncoding(new
			 * BasicHeader( HTTP.CONTENT_TYPE, "application/json"));
			 * entity.setContentType("application/json");
			 * 
			 * request.setEntity(entity);
			 * 
			 * // Send request to WCF service DefaultHttpClient httpClient = new
			 * DefaultHttpClient();
			 * 
			 * try { Log.e("response", "connect"); HttpResponse response =
			 * httpClient.execute(request); //
			 * ===========================================================
			 * HttpEntity entitye = response.getEntity(); is =
			 * entity.getContent(); if (is != null) {
			 * 
			 * try { BufferedReader reader = new BufferedReader( new
			 * InputStreamReader(is, "iso-8859-1"), 8); sb = new
			 * StringBuilder(); sb.append(reader.readLine() + "\n"); String line
			 * = "0"; while ((line = reader.readLine()) != null) {
			 * sb.append(line + "\n"); } is.close(); String result =
			 * sb.toString(); Log.e("String Responce", "Print Responce:" +
			 * result); } catch (Exception e1) { e1.printStackTrace(); } } //
			 * ================================== Log.e("response",
			 * "response get:" + response.toString()); //
			 * System.out.println(response.toString()); BufferedReader reader =
			 * new BufferedReader( new InputStreamReader(response.getEntity()
			 * .getContent(), "UTF-8")); String json = reader.readLine(); String
			 * CheckStateDet = json.toString().replaceAll( "[\'\"]", ""); if
			 * (CheckStateDet.equals("200")) { Log.v(TAG,
			 * "STOCK_LOAD_HEADDAM**:" + CheckStateDet); ContentValues
			 * changeSyncStatefLoadDet = new ContentValues();
			 * changeSyncStatefLoadDet.put("adjHedSync", "1");
			 * mydb.update(ADJUST_ADDITION_HEADER, changeSyncStatefLoadDet,
			 * "fadjhed_id ='" + FAdjAdditionHedIndex + "'", null); }
			 * 
			 * Log.e("json string", "test " + json.toString() + " lazim");
			 * System.out.println(json); } catch (Exception e) {
			 * e.printStackTrace(); } } arrayLength = 7; progressHandler
			 * .sendMessage(progressHandler.obtainMessage()); }
			 * 
			 * }
			 */
			// =================================
			if (selectOrderHeader != null) {
				if (selectOrderHeader.getCount() > 0) {
					while (selectOrderHeader.moveToNext()) {

						FStoOrdersHedIndex = selectOrderHeader.getString(0);
						String AddMach = selectOrderHeader.getString(1);
						String AddUser = selectOrderHeader.getString(2);
						String AreaCode = selectOrderHeader.getString(3);
						String CostCode = selectOrderHeader.getString(4);
						String CurCode = selectOrderHeader.getString(5);
						String CurRate = selectOrderHeader.getString(6);
						String DealCode = selectOrderHeader.getString(7);
						String DebCode = selectOrderHeader.getString(8);
						String InvAmt = selectOrderHeader.getString(9);

						String InvDis = selectOrderHeader.getString(10);
						double InvDisVal = Double.parseDouble(InvDis
								.replaceAll("[,]", ""));

						String InvFlg = selectOrderHeader.getString(11);
						String LocCode = selectOrderHeader.getString(12);
						String ManuRef = selectOrderHeader.getString(13);
						String OutDis = selectOrderHeader.getString(14);
						String RecordId = selectOrderHeader.getString(15);
						String RefNo = selectOrderHeader.getString(16);
						String Remarks = selectOrderHeader.getString(17);
						String RepCode = selectOrderHeader.getString(18);
						String RouteCode = selectOrderHeader.getString(19);
						String TotMkrAmt = selectOrderHeader.getString(20);
						String TotalAmt = selectOrderHeader.getString(21);

						String TotalDis = selectOrderHeader.getString(22);
						double TotalDisVal = Double.parseDouble(TotalDis
								.replaceAll("[,]", ""));

						String TranBatch = selectOrderHeader.getString(23);
						String TxnType = selectOrderHeader.getString(24);
						String UnOvAmt = selectOrderHeader.getString(25);
						String prtcopy = selectOrderHeader.getString(26);
						String TxnDate = selectOrderHeader.getString(27);

						String outDisVal = selectOrderHeader.getString(30);

						UploadodAddDate = selectOrderHeader.getString(31);
						String DeliverAddDate = selectOrderHeader.getString(32);

						try {
							date = originalFormat.parse(DeliverAddDate
									.replaceAll("[-+/.^:,]", " "));
							DeliverAddDate = targetFormat.format(date);

						} catch (ParseException ex) {
						}

						Log.v(TAG, "DDDD :" + UploadodAddDate);
						try {
							if (UploadodAddDate.equals(null)) {
								UploadodAddDate = getAddDateTimeString()
										.toString();
							}
						} catch (Exception ex) {
							UploadodAddDate = getAddDateTimeString().toString();
						}
						/*
						 * if(UploadodAddDate.equals(null)){ UploadodAddDate =
						 * getAddDateTimeString().toString(); }
						 */
						double outDisValue = Double.parseDouble(outDisVal
								.replaceAll("[,]", ""));
						// Line Items Discount
						double LineItemsDis = TotalDisVal
								- (InvDisVal + outDisValue);
						String LineItemsDisString = Double
								.toString(LineItemsDis);

						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						// Upload record
						HttpPost request = new HttpPost(
								connectionURL
										+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/updateFOrdHed");

						JSONStringer userJson = null;

						try {
							count = count + 1;
							Log.e("json", "Count:" + count);
							userJson = new JSONStringer()
									.object()
									.key("fOHed")
									.object()
									.key("RefNo")
									.value(RefNo)
									.key("TxnDate")
									.value(TxnDate)
									.key("ManuRef")
									.value(ManuRef)
									.key("DelvDate")
									.value(DeliverAddDate)
									.key("DealCode")
									.value(AgentDealCode)
									.key("RepCode")
									.value(RepCode)
									.key("AreaCode")
									.value(AreaCode)
									.key("RouteCode")
									.value(RepRouteCode)
									.key("DebCode")
									.value(DebCode)
									.key("LocCode")
									.value(LocCode)
									.key("Remarks")
									.value(Remarks)
									.key("CostCode")
									.value(CostCode)
									.key("CurCode")
									.value(CurCode)
									.key("CurRate")
									.value(CurRate)
									.key("TxnType")
									.value(TxnType)
									.key("InvAmt")
									.value(InvAmt.replaceAll("[,]", ""))
									.key("OutDis")
									.value(OutDis.replaceAll("[,]", ""))
									.key("InvDis")
									.value(InvDis.replaceAll("[,]", ""))
									.key("TotMkrAmt")
									.value(TotMkrAmt.replaceAll("[,]", ""))
									.key("UnOvAmt")
									.value(UnOvAmt.replaceAll("[,]", ""))
									.key("TotalDis")
									.value(TotalDis.replaceAll("[,]", ""))
									.key("TotalItmDis")
									.value(LineItemsDisString.replaceAll("[,]",
											"")).key("TotalAmt")
									.value(TotalAmt.replaceAll("[,]", ""))
									.key("AddUser").value(AddUser)
									.key("AddMach").value(AddMach)
									.key("prtcopy").value(prtcopy)
									.key("InvFlg").value(InvFlg)
									.key("RecordId").value(RecordId)
									.key("TranBatch").value(TranBatch)
									.key("OutDisVal").value(outDisValue)
									.key("AddDate").value(UploadodAddDate)
									.key("DbName").value(currentUserServerDB)
									.endObject();
							Log.e("json", "json created");
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						StringEntity entity = null;
						try {
							entity = new StringEntity(userJson.toString(),
									"UTF-8");
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						entity.setContentEncoding(new BasicHeader(
								HTTP.CONTENT_TYPE, "application/json"));
						entity.setContentType("application/json");

						request.setEntity(entity);

						// Send request to WCF service
						DefaultHttpClient httpClient = new DefaultHttpClient();

						try {
							Log.e("response", "connect");
							HttpResponse response = httpClient.execute(request);

							// ===========================================================
							HttpEntity entitye = response.getEntity();
							is = entity.getContent();
							if (is != null) {

								try {
									BufferedReader reader = new BufferedReader(
											new InputStreamReader(is,
													"iso-8859-1"), 8);
									sb = new StringBuilder();
									sb.append(reader.readLine() + "\n");
									String line = "0";
									while ((line = reader.readLine()) != null) {
										sb.append(line + "\n");
									}
									is.close();
									String result = sb.toString();
									Log.e("String Responce", "Print Responce:"
											+ result);
								} catch (Exception e1) {
									e1.printStackTrace();
								}
							}
							// ==================================
							Log.e(" ", "Res:" + response.toString());
							// System.out.println(response.toString());
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(response.getEntity()
											.getContent(), "UTF-8"));
							String json = reader.readLine();

							String CheckStateDet = json.toString().replaceAll(
									"[\'\"]", "");
							if (CheckStateDet.equals("200")) {
								Log.v(TAG, "STOCK_ORDER_HEAD**:"
										+ CheckStateDet);
								ContentValues changeSyncStatefLoadDet = new ContentValues();
								changeSyncStatefLoadDet
										.put("stordhedSync", "1");
								mydb.update(STOCK_ORDER_HEAD,
										changeSyncStatefLoadDet, "stohed_id ='"
												+ FStoOrdersHedIndex + "'",
										null);
							}
							Log.e("json string", "test " + json.toString()
									+ " lazim");
							System.out.println(json);
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
					arrayLength = 14;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}

			}

			// ----------_________----------_____________
			mydb.close();
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
			SynchDetails.dismiss();
			new UploadingInvoiceDetailsData().execute();
		}
	}

	private class UploadingInvoiceDetailsData extends
			AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(DM_InvoiceMenu.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Uploading");
			// Set progressdialog message
			mProgressDialog.setMessage("Uploading Invoice Details...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

			Cursor selectInvDetailsData = null;
			Cursor selectStockLoadDetails = null;
			Cursor selectStockUnLoadDetails = null;
			Cursor selectInvReceiptDetails = null;
			Cursor selectDamageTransferDetails = null;
			Cursor selectAdjustmentDetails = null;
			Cursor selectOrderDetails = null;
			try {
				selectInvDetailsData = mydb.query(INV_DETAILS, null,
						"invdetSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}
			try {
				selectStockLoadDetails = mydb.query(STOCK_LOAD_DETAIL, null,
						"stldetSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}
			try {
				selectStockUnLoadDetails = mydb.query(STOCK_LOAD_DETAILUN,
						null, "stldetunSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}
			try {
				selectInvReceiptDetails = mydb.query(RECEIPT_DETAILS, null,
						"reciptdetSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}

			try {
				selectDamageTransferDetails = mydb.query(STOCK_LOAD_DETAILDAM,
						null, "stldmdetSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}

			try {
				selectAdjustmentDetails = mydb.query(ADJUST_ADDITION_DETAILS,
						null, "adjDetSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}

			try {
				selectOrderDetails = mydb.query(STOCK_ORDER_DETAIL, null,
						"storddetSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}
			// ================Upload invoice details===================
			if (selectInvDetailsData != null) {
				if (selectInvDetailsData.getCount() > 0) {
					while (selectInvDetailsData.moveToNext()) {

						FInvDetIndex = selectInvDetailsData.getString(0);
						String RefNo = selectInvDetailsData.getString(1);
						String TxnDate = selectInvDetailsData.getString(2);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String TxnType = selectInvDetailsData.getString(3);
						String SeqNo = selectInvDetailsData.getString(4);
						String Itemcode = selectInvDetailsData.getString(5);
						String Txnseqno = selectInvDetailsData.getString(6);
						String SellPrice = selectInvDetailsData.getString(7);
						String BSellPrice = selectInvDetailsData.getString(8);
						String TSellPrice = selectInvDetailsData.getString(9);
						String BTSellPrice = selectInvDetailsData.getString(10);
						String CostPrice = selectInvDetailsData.getString(11);
						String CaseQty = selectInvDetailsData.getString(12);
						String Type = selectInvDetailsData.getString(13);
						String PiceQty = selectInvDetailsData.getString(14);
						String Qty = selectInvDetailsData.getString(15);
						String BalQty = selectInvDetailsData.getString(16);
						String DisPer = selectInvDetailsData.getString(17);
						String DisAmt = selectInvDetailsData.getString(18);
						String BDisAmt = selectInvDetailsData.getString(19);
						String TaxAmt = selectInvDetailsData.getString(20);
						String BTaxAmt = selectInvDetailsData.getString(21);
						String Amt = selectInvDetailsData.getString(22);
						String BAmt = selectInvDetailsData.getString(23);
						String ReaCode = selectInvDetailsData.getString(24);
						String Linkrec = selectInvDetailsData.getString(25);
						String RecordId = selectInvDetailsData.getString(26);
						String itemDescription = selectInvDetailsData
								.getString(27);
						String refInvoiceDetNo = selectInvDetailsData
								.getString(28);
						String refInvoiceDetCode = selectInvDetailsData
								.getString(29);
						String refInvitemCaseQty = selectInvDetailsData
								.getString(30);
						String invDetAddDate = selectInvDetailsData
								.getString(33);
						String itemdisper = selectInvDetailsData.getString(34);

						String itemdisperval = "0", DisValueAmtCalStr = "0";
						try {
							itemdisperval = selectInvDetailsData.getString(35);
							double totlineItemDis = Double.parseDouble(BDisAmt
									.replaceAll("[,]", ""));
							double DisPerAmount = Double
									.parseDouble(itemdisperval.replaceAll(
											"[,]", ""));
							double DisValueAmtCal = totlineItemDis
									- DisPerAmount;
							DisValueAmtCalStr = Double.toString(DisValueAmtCal);
						} catch (Exception e) {
							Log.e("RES DJ2:", "Upload Rallback");
						}

						String reasonCode = selectInvDetailsData.getString(36);
						HttpPost request = new HttpPost(
								connectionURL
										+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/insertFinvDet");

						JSONStringer userJson = null;

						try {

							countdet = countdet + 1;
							Log.e("C", "Countdet :" + countdet);
							userJson = new JSONStringer()
									.object()
									.key("fDet")
									.object()
									.key("RefNo")
									.value(refInvoiceDetCode)
									.key("TxnDate")
									.value(TxnDate)
									.key("TxnType")
									.value(TxnType)
									.key("SeqNo")
									.value(SeqNo)
									.key("Itemcode")
									.value(Itemcode)
									.key("Txnseqno")
									.value(Txnseqno)
									.key("SellPrice")
									.value(SellPrice.replaceAll("[,]", ""))
									.key("BSellPrice")
									.value(BSellPrice.replaceAll("[,]", ""))
									.key("TSellPrice")
									.value(TSellPrice.replaceAll("[,]", ""))
									.key("BTSellPrice")
									.value(BTSellPrice.replaceAll("[,]", ""))
									.key("CostPrice")
									.value(CostPrice.replaceAll("[,]", ""))
									.key("CaseQty")
									.value(CaseQty.replaceAll("[,]", ""))
									.key("PiceQty")
									.value(PiceQty.replaceAll("[,]", ""))
									.key("Type")
									.value(Type)
									.key("Qty")
									.value(Qty.replaceAll("[,]", ""))
									.key("BalQty")
									.value(BalQty.replaceAll("[,]", ""))
									.key("DisPer")
									.value(DisPer.replaceAll("[,]", ""))
									.key("DisAmt")
									.value(DisAmt.replaceAll("[,]", ""))
									.key("BDisAmt")
									.value(BDisAmt.replaceAll("[,]", ""))
									.key("TaxAmt")
									.value(TaxAmt.replaceAll("[,]", ""))
									.key("BTaxAmt")
									.value(BTaxAmt.replaceAll("[,]", ""))
									.key("Amt")
									.value(Amt.replaceAll("[,]", ""))
									.key("BAmt")
									.value(BAmt.replaceAll("[,]", ""))
									.key("ReaCode")
									.value(ReaCode)
									.key("Linkrec")
									.value("0")
									.key("DisPerAmt")
									.value(itemdisperval.replaceAll("[,]", ""))
									.key("DisValAmt")
									.value(DisValueAmtCalStr.replaceAll("[,]",
											"")).key("LocCode")
									.value(UserLocCode).key("DbName")
									.value(currentUserServerDB).endObject();

							// DisPerAmt , DisValAmt
							// .key("RecordId").value("10")
							Log.e("json", "json created");
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						StringEntity entity = null;
						try {
							entity = new StringEntity(userJson.toString(),
									"UTF-8");
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						entity.setContentEncoding(new BasicHeader(
								HTTP.CONTENT_TYPE, "application/json"));
						entity.setContentType("application/json");

						request.setEntity(entity);

						// Send request to WCF service
						DefaultHttpClient httpClient = new DefaultHttpClient();

						try {
							Log.e("response", "connect");
							HttpResponse response = httpClient.execute(request);
							// ===========================================================
							HttpEntity entitye = response.getEntity();
							is = entity.getContent();
							if (is != null) {

								try {
									BufferedReader reader = new BufferedReader(
											new InputStreamReader(is,
													"iso-8859-1"), 8);
									sb = new StringBuilder();
									sb.append(reader.readLine() + "\n");
									String line = "0";
									while ((line = reader.readLine()) != null) {
										sb.append(line + "\n");
									}
									is.close();
									String result = sb.toString();
									Log.e("String Responce", "Print Responce:"
											+ result);
								} catch (Exception e1) {
									e1.printStackTrace();
								}
							}
							// ==================================
							Log.e("response",
									"response get:" + response.toString());
							// System.out.println(response.toString());
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(response.getEntity()
											.getContent(), "UTF-8"));
							String json = reader.readLine();
							String CheckStateDet = json.toString().replaceAll(
									"[\'\"]", "");
							if (CheckStateDet.equals("200")) {
								ContentValues changeSyncStatefLoadDet = new ContentValues();
								changeSyncStatefLoadDet.put("invdetSync", "1");
								mydb.update(INV_DETAILS,
										changeSyncStatefLoadDet, "invdet_id ='"
												+ FInvDetIndex + "'", null);
							}
							Log.e("json string", "test " + json.toString()
									+ " lazim");
							System.out.println(json);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}
				selectInvDetailsData.close();
			}
			// ================Upload Stock Loading details===================
			if (selectStockLoadDetails != null) {
				if (selectStockLoadDetails.getCount() > 0) {
					while (selectStockLoadDetails.moveToNext()) {
						LoadingDetailsIndex = selectStockLoadDetails
								.getString(0);
						String RefNo = selectStockLoadDetails.getString(1);
						String TxnDate = selectStockLoadDetails.getString(2);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String LocCode = selectStockLoadDetails.getString(3);
						String TxnType = selectStockLoadDetails.getString(4);
						String SeqNo = selectStockLoadDetails.getString(5);
						String ItemCode = selectStockLoadDetails.getString(6);
						String CaseQty = selectStockLoadDetails.getString(7);
						String PiceQty = selectStockLoadDetails.getString(8);
						String Qty = selectStockLoadDetails.getString(9);
						String CostPrice = selectStockLoadDetails.getString(10);
						String Amt = selectStockLoadDetails.getString(11);
						String RecordChecked = selectStockLoadDetails
								.getString(13);
						HttpPost request = new HttpPost(
								connectionURL
										+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/insertfLoadDet");

						JSONStringer userJson = null;

						try {

							userJson = new JSONStringer().object().key("fLDet")
									.object().key("RefNo").value(RefNo)
									.key("TxnDate").value(TxnDate)
									.key("LocCode").value(LocCode)
									.key("TxnType").value(TxnType).key("SeqNo")
									.value(SeqNo).key("ItemCode")
									.value(ItemCode).key("CaseQty")
									.value(CaseQty.replaceAll("[,]", ""))
									.key("PiceQty")
									.value(PiceQty.replaceAll("[,]", ""))
									.key("Qty").value(Qty).key("CostPrice")
									.value(CostPrice.replaceAll("[,]", ""))
									.key("Amt")
									.value(Amt.replaceAll("[,]", ""))
									.key("RecordChecked").value(RecordChecked)
									.key("DbName").value(currentUserServerDB)
									.endObject();
							Log.e("json", "json created");
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						StringEntity entity = null;
						try {
							entity = new StringEntity(userJson.toString(),
									"UTF-8");
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						entity.setContentEncoding(new BasicHeader(
								HTTP.CONTENT_TYPE, "application/json"));
						entity.setContentType("application/json");

						request.setEntity(entity);

						// Send request to WCF service
						DefaultHttpClient httpClient = new DefaultHttpClient();

						try {
							Log.e("response", "connect");
							HttpResponse response = httpClient.execute(request);
							// ===========================================================
							HttpEntity entitye = response.getEntity();
							is = entity.getContent();
							if (is != null) {

								try {
									BufferedReader reader = new BufferedReader(
											new InputStreamReader(is,
													"iso-8859-1"), 8);
									sb = new StringBuilder();
									sb.append(reader.readLine() + "\n");
									String line = "0";
									while ((line = reader.readLine()) != null) {
										sb.append(line + "\n");
									}
									is.close();
									String result = sb.toString();

									Log.e("String Responce", "Print Responce:"
											+ result);
								} catch (Exception e1) {
									e1.printStackTrace();
								}
							}
							// ==================================
							Log.e("response",
									"response get:" + response.toString());
							// System.out.println(response.toString());
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(response.getEntity()
											.getContent(), "UTF-8"));
							String json = reader.readLine();
							String CheckStateDet = json.toString().replaceAll(
									"[\'\"]", "");
							if (CheckStateDet.equals("200")) {
								Log.v(TAG, "STOCK_LOAD_DETAIL**:"
										+ CheckStateDet);
								ContentValues changeSyncStatefLoadDet = new ContentValues();
								changeSyncStatefLoadDet.put("stldetSync", "1");
								mydb.update(STOCK_LOAD_DETAIL,
										changeSyncStatefLoadDet, "RecordId ='"
												+ LoadingDetailsIndex + "'",
										null);
							}
							Log.e("json string", "test " + json.toString()
									+ " lazim");
							System.out.println(json);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
				arrayLength = 7;
				progressHandler.sendMessage(progressHandler.obtainMessage());
				selectStockLoadDetails.close();
			}

			// ================Upload Stock UnLoading details===================
			if (selectStockUnLoadDetails != null) {
				if (selectStockUnLoadDetails.getCount() > 0) {
					while (selectStockUnLoadDetails.moveToNext()) {

						FStoUnloadDetIndex = selectStockUnLoadDetails
								.getString(0);
						String RefNo = selectStockUnLoadDetails.getString(1);
						String TxnDate = selectStockUnLoadDetails.getString(2);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String LocCode = selectStockUnLoadDetails.getString(3);
						String TxnType = selectStockUnLoadDetails.getString(4);
						String SeqNo = selectStockUnLoadDetails.getString(5);
						String ItemCode = selectStockUnLoadDetails.getString(6);
						String CaseQty = selectStockUnLoadDetails.getString(7);
						String PiceQty = selectStockUnLoadDetails.getString(8);
						String Qty = selectStockUnLoadDetails.getString(9);
						String CostPrice = selectStockUnLoadDetails
								.getString(10);
						String Amt = selectStockUnLoadDetails.getString(11);
						String RecordChecked = selectStockUnLoadDetails
								.getString(13);
						String IntangFlg = selectStockUnLoadDetails
								.getString(18);
						HttpPost request = new HttpPost(
								connectionURL
										+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/insertfUnLoadDet");

						JSONStringer userJson = null;

						try {
							userJson = new JSONStringer().object()
									.key("fULDet").object().key("RefNo")
									.value(RefNo).key("TxnDate").value(TxnDate)
									.key("LocCode").value(LocCode)
									.key("TxnType").value(TxnType).key("SeqNo")
									.value(SeqNo).key("ItemCode")
									.value(ItemCode).key("CaseQty")
									.value(CaseQty).key("PiceQty")
									.value(PiceQty.replaceAll("[,]", ""))
									.key("Qty")
									.value(Qty.replaceAll("[,]", ""))
									.key("CostPrice")
									.value(CostPrice.replaceAll("[,]", ""))
									.key("Amt")
									.value(Amt.replaceAll("[,]", ""))
									.key("RecordChecked").value(RecordChecked)
									.key("IntangFlg").value(IntangFlg)
									.key("DbName").value(currentUserServerDB)
									.endObject();
							// .key("RecordId").value("10")
							Log.e("json", "json created");
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						StringEntity entity = null;
						try {
							entity = new StringEntity(userJson.toString(),
									"UTF-8");
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						entity.setContentEncoding(new BasicHeader(
								HTTP.CONTENT_TYPE, "application/json"));
						entity.setContentType("application/json");

						request.setEntity(entity);

						// Send request to WCF service
						DefaultHttpClient httpClient = new DefaultHttpClient();

						try {
							Log.e("response", "connect");
							HttpResponse response = httpClient.execute(request);
							// ===========================================================
							HttpEntity entitye = response.getEntity();
							is = entity.getContent();
							if (is != null) {

								try {
									BufferedReader reader = new BufferedReader(
											new InputStreamReader(is,
													"iso-8859-1"), 8);
									sb = new StringBuilder();
									sb.append(reader.readLine() + "\n");
									String line = "0";
									while ((line = reader.readLine()) != null) {
										sb.append(line + "\n");
									}
									is.close();
									String result = sb.toString();
									Log.e("String Responce", "Print Responce:"
											+ result);
								} catch (Exception e1) {
									e1.printStackTrace();
								}
							}
							// ==================================
							Log.e("response",
									"response get:" + response.toString());
							// System.out.println(response.toString());
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(response.getEntity()
											.getContent(), "UTF-8"));
							String json = reader.readLine();
							String CheckStateDet = json.toString().replaceAll(
									"[\'\"]", "");
							if (CheckStateDet.equals("200")
									|| CheckStateDet.equals("500")) {
								ContentValues changeSyncStatefLoadDet = new ContentValues();
								changeSyncStatefLoadDet
										.put("stldetunSync", "1");
								mydb.update(STOCK_LOAD_DETAILUN,
										changeSyncStatefLoadDet, "RecordId ='"
												+ FStoUnloadDetIndex + "'",
										null);
							}
							Log.e("json string", "test " + json.toString()
									+ " lazim");
							System.out.println(json);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}
				selectStockUnLoadDetails.close();
			}

			// ================Upload Receipt details===================
			if (selectInvReceiptDetails != null) {
				if (selectInvReceiptDetails.getCount() > 0) {
					while (selectInvReceiptDetails.moveToNext()) {

						FReceiptDetIndex = selectInvReceiptDetails.getString(0);
						String RefNo = selectInvReceiptDetails.getString(1);
						String RefNo1 = selectInvReceiptDetails.getString(2);
						String SaleRefNo = selectInvReceiptDetails.getString(3);
						String ManuRef = selectInvReceiptDetails.getString(4);
						String TxnType = selectInvReceiptDetails.getString(5);
						String TxnDate = selectInvReceiptDetails.getString(6);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String DtxnDate = selectInvReceiptDetails.getString(7);
						try {
							date = originalFormat.parse(DtxnDate.replaceAll(
									"[-+/.^:,]", " "));
							DtxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							DtxnDate = "1900-01-01";
						}
						String DtxnType = selectInvReceiptDetails.getString(8);
						String DCurCode = selectInvReceiptDetails.getString(9);
						String DCurRate = selectInvReceiptDetails.getString(10);
						String OCurRate = selectInvReceiptDetails.getString(11);
						String RepCode = selectInvReceiptDetails.getString(12);
						String Amt = selectInvReceiptDetails.getString(13);
						String BAmt = selectInvReceiptDetails.getString(14);
						String GainLosAmt = selectInvReceiptDetails
								.getString(15);
						String BnkChgs = selectInvReceiptDetails.getString(16);
						String BBnkChgs = selectInvReceiptDetails.getString(17);
						String AloAmt = selectInvReceiptDetails.getString(18);
						String OvPayAmt = selectInvReceiptDetails.getString(19);
						String OvPayBal = selectInvReceiptDetails.getString(20);

						// Upload record
						HttpPost request = new HttpPost(
								connectionURL
										+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/insertfdrecdet");

						JSONStringer userJson = null;

						try {
							count = count + 1;
							Log.e("json", "Count:" + count);
							userJson = new JSONStringer().object()
									.key("fDRDet").object().key("RefNo")
									.value(RefNo).key("RefNo1").value(RefNo1)
									.key("SaleRefNo").value(SaleRefNo)
									.key("ManuRef").value(ManuRef)
									.key("TxnType").value(TxnType)
									.key("TxnDate").value(TxnDate)
									.key("DtxnDate").value(DtxnDate)
									.key("DtxnType").value(DtxnType)
									.key("DCurCode").value(DCurCode)
									.key("DCurRate")
									.value(DCurRate.replaceAll("[,]", ""))
									.key("OCurRate")
									.value(OCurRate.replaceAll("[,]", ""))
									.key("RepCode").value(RepCode).key("Amt")
									.value(Amt.replaceAll("[,]", ""))
									.key("BAmt")
									.value(BAmt.replaceAll("[,]", ""))
									.key("GainLosAmt")
									.value(GainLosAmt.replaceAll("[,]", ""))
									.key("BnkChgs")
									.value(BnkChgs.replaceAll("[,]", ""))
									.key("BBnkChgs")
									.value(BBnkChgs.replaceAll("[,]", ""))
									.key("AloAmt")
									.value(AloAmt.replaceAll("[,]", ""))
									.key("OvPayAmt")
									.value(OvPayAmt.replaceAll("[,]", ""))
									.key("OvPayBal")
									.value(OvPayBal.replaceAll("[,]", ""))
									.key("DbName").value(currentUserServerDB)
									.endObject();
							Log.e("json", "json created");
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						StringEntity entity = null;
						try {
							entity = new StringEntity(userJson.toString(),
									"UTF-8");
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						entity.setContentEncoding(new BasicHeader(
								HTTP.CONTENT_TYPE, "application/json"));
						entity.setContentType("application/json");

						request.setEntity(entity);

						// Send request to WCF service
						DefaultHttpClient httpClient = new DefaultHttpClient();

						try {
							Log.e("response", "connect");
							HttpResponse response = httpClient.execute(request);

							// ===========================================================
							HttpEntity entitye = response.getEntity();
							is = entity.getContent();
							if (is != null) {

								try {
									BufferedReader reader = new BufferedReader(
											new InputStreamReader(is,
													"iso-8859-1"), 8);
									sb = new StringBuilder();
									sb.append(reader.readLine() + "\n");
									String line = "0";
									while ((line = reader.readLine()) != null) {
										sb.append(line + "\n");
									}
									is.close();
									String result = sb.toString();
									Log.e("String Responce", "Print Responce:"
											+ result);
								} catch (Exception e1) {
									e1.printStackTrace();
								}
							}
							// ==================================
							Log.e(" ", "Res:" + response.toString());
							// System.out.println(response.toString());
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(response.getEntity()
											.getContent(), "UTF-8"));
							String json = reader.readLine();
							String CheckStateDet = json.toString().replaceAll(
									"[\'\"]", "");
							if (CheckStateDet.equals("200")) {
								ContentValues changeSyncStatefLoadDet = new ContentValues();
								changeSyncStatefLoadDet.put("reciptdetSync",
										"1");
								mydb.update(RECEIPT_DETAILS,
										changeSyncStatefLoadDet, "RecDet_id ='"
												+ FReceiptDetIndex + "'", null);
							}
							Log.e("json string", "test " + json.toString()
									+ " lazim");
							System.out.println(json);
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}
				selectInvReceiptDetails.close();
			}

			// ================Upload Receipt details===================
			if (selectDamageTransferDetails != null) {
				if (selectDamageTransferDetails.getCount() > 0) {
					while (selectDamageTransferDetails.moveToNext()) {

						FDamageDetIndex = selectDamageTransferDetails
								.getString(0);
						String RefNo = selectDamageTransferDetails.getString(1);
						String TxnDate = selectDamageTransferDetails
								.getString(2);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String LocCode = selectDamageTransferDetails
								.getString(3);
						String TxnType = selectDamageTransferDetails
								.getString(4);
						String SeqNo = selectDamageTransferDetails.getString(5);
						String ItemCode = selectDamageTransferDetails
								.getString(6);
						String CaseQty = selectDamageTransferDetails
								.getString(7);
						String PiceQty = selectDamageTransferDetails
								.getString(8);
						String Qty = selectDamageTransferDetails.getString(9);
						String CostPrice = selectDamageTransferDetails
								.getString(10);
						String Amt = selectDamageTransferDetails.getString(11);
						String reaCode = selectDamageTransferDetails
								.getString(17);
						// Upload record
						HttpPost request = new HttpPost(
								connectionURL
										+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/insertfDamDet");

						JSONStringer userJson = null;
						try {
							count = count + 1;
							Log.e("json", "Count:" + count);
							userJson = new JSONStringer().object().key("fDDet")
									.object().key("RefNo").value(RefNo)
									.key("TxnDate").value(TxnDate)
									.key("LocCode").value(LocCode)
									.key("TxnType").value(TxnType).key("SeqNo")
									.value(SeqNo).key("ItemCode")
									.value(ItemCode).key("CaseQty")
									.value(CaseQty).key("PiceQty")
									.value(PiceQty.replaceAll("[,]", ""))
									.key("Qty").value(Qty).key("CostPrice")
									.value(CostPrice.replaceAll("[,]", ""))
									.key("Amt")
									.value(Amt.replaceAll("[,]", ""))
									.key("ReaCode").value(reaCode)
									.key("DbName").value(currentUserServerDB)
									.endObject();
							Log.e("json", "json created");
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						StringEntity entity = null;
						try {
							entity = new StringEntity(userJson.toString(),
									"UTF-8");
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						entity.setContentEncoding(new BasicHeader(
								HTTP.CONTENT_TYPE, "application/json"));
						entity.setContentType("application/json");

						request.setEntity(entity);

						// Send request to WCF service
						DefaultHttpClient httpClient = new DefaultHttpClient();

						try {
							Log.e("response", "connect");
							HttpResponse response = httpClient.execute(request);

							// ===========================================================
							HttpEntity entitye = response.getEntity();
							is = entity.getContent();
							if (is != null) {

								try {
									BufferedReader reader = new BufferedReader(
											new InputStreamReader(is,
													"iso-8859-1"), 8);
									sb = new StringBuilder();
									sb.append(reader.readLine() + "\n");
									String line = "0";
									while ((line = reader.readLine()) != null) {
										sb.append(line + "\n");
									}
									is.close();
									String result = sb.toString();
									Log.e("String Responce", "Print Responce:"
											+ result);
								} catch (Exception e1) {
									e1.printStackTrace();
								}
							}
							// ==================================
							Log.e(" ", "Res:" + response.toString());
							// System.out.println(response.toString());
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(response.getEntity()
											.getContent(), "UTF-8"));
							String json = reader.readLine();
							String CheckStateDet = json.toString().replaceAll(
									"[\'\"]", "");
							if (CheckStateDet.equals("200")) {
								ContentValues changeSyncStatefLoadDet = new ContentValues();
								changeSyncStatefLoadDet
										.put("stldmdetSync", "1");
								mydb.update(STOCK_LOAD_DETAILDAM,
										changeSyncStatefLoadDet, "RecordId ='"
												+ FDamageDetIndex + "'", null);
							}
							Log.e("json string", "test " + json.toString()
									+ " lazim");
							System.out.println(json);
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}

			}

			/*
			 * // ******Upload fAdjDet************** if (selectAdjustmentDetails
			 * != null) { if (selectAdjustmentDetails.getCount() > 0) { while
			 * (selectAdjustmentDetails.moveToNext()) { FAdjAdditionDetIndex =
			 * selectAdjustmentDetails .getString(0); String RefNo =
			 * selectAdjustmentDetails.getString(1); String TxnDate =
			 * selectAdjustmentDetails.getString(2); try { date =
			 * originalFormat.parse(TxnDate.replaceAll( "[-+/.^:,]", " "));
			 * TxnDate = targetFormat.format(date);
			 * 
			 * } catch (ParseException ex) { TxnDate = "1900-01-01"; } String
			 * TxnType = selectAdjustmentDetails.getString(3); String SeqNo =
			 * selectAdjustmentDetails.getString(4); String ItemCode =
			 * selectAdjustmentDetails.getString(5); String CaseQty =
			 * selectAdjustmentDetails.getString(6); String PiceQty =
			 * selectAdjustmentDetails.getString(7); String Qty =
			 * selectAdjustmentDetails.getString(8); String CostPrice =
			 * selectAdjustmentDetails.getString(9); String Amt =
			 * selectAdjustmentDetails.getString(10); String ReaCode =
			 * selectAdjustmentDetails.getString(11);
			 * 
			 * try { String queryAdjhed =
			 * "SELECT RefNo,LocCode from FAdjHed Where RefNo = '" + RefNo +
			 * "'"; Cursor cursorAdjhed = null; cursorAdjhed =
			 * mydb.rawQuery(queryAdjhed, null); if (cursorAdjhed != null &&
			 * cursorAdjhed.getCount() > 0) { while (cursorAdjhed.moveToNext())
			 * { CurrentAdjLocation = cursorAdjhed .getString(1); } } } catch
			 * (Exception e) { }
			 * 
			 * HttpPost request = new HttpPost( connectionURL +
			 * "/PDADBWebServiceN/PDADBWebServiceRest.svc/insertfAdjDet");
			 * 
			 * JSONStringer userJson = null; try { userJson = new
			 * JSONStringer().object() .key("faddet").object().key("RefNo")
			 * .value(RefNo).key("TxnDate").value(TxnDate)
			 * .key("TxnType").value(TxnType).key("SeqNo")
			 * .value(SeqNo).key("ItemCode") .value(ItemCode).key("CaseQty")
			 * .value(CaseQty.replaceAll("[,]", "")) .key("PiceQty")
			 * .value(PiceQty.replaceAll("[,]", ""))
			 * .key("Qty").value(Qty).key("CostPrice")
			 * .value(CostPrice.replaceAll("[,]", "")) .key("Amt")
			 * .value(Amt.replaceAll("[,]", "")) .key("ReaCode").value(ReaCode)
			 * .key("LocCode").value(CurrentAdjLocation)
			 * .key("DbName").value(currentUserServerDB) .endObject(); //
			 * .key("RecordId").value("10") Log.e("json", "json created"); }
			 * catch (JSONException e) {
			 * 
			 * // TODO Auto-generated catch block e.printStackTrace(); }
			 * 
			 * StringEntity entity = null; try { entity = new
			 * StringEntity(userJson.toString(), "UTF-8"); } catch
			 * (UnsupportedEncodingException e) { // TODO Auto-generated catch
			 * block e.printStackTrace(); } entity.setContentEncoding(new
			 * BasicHeader( HTTP.CONTENT_TYPE, "application/json"));
			 * entity.setContentType("application/json");
			 * 
			 * request.setEntity(entity);
			 * 
			 * // Send request to WCF service DefaultHttpClient httpClient = new
			 * DefaultHttpClient();
			 * 
			 * try { Log.e("response", "connect"); HttpResponse response =
			 * httpClient.execute(request); //
			 * ===========================================================
			 * HttpEntity entitye = response.getEntity(); is =
			 * entity.getContent(); if (is != null) {
			 * 
			 * try { BufferedReader reader = new BufferedReader( new
			 * InputStreamReader(is, "iso-8859-1"), 8); sb = new
			 * StringBuilder(); sb.append(reader.readLine() + "\n"); String line
			 * = "0"; while ((line = reader.readLine()) != null) {
			 * sb.append(line + "\n"); } is.close(); String result =
			 * sb.toString(); Log.e("String Responce", "Print Responce:" +
			 * result); } catch (Exception e1) { e1.printStackTrace(); } } //
			 * ================================== Log.e("response",
			 * "response get:" + response.toString()); //
			 * System.out.println(response.toString()); BufferedReader reader =
			 * new BufferedReader( new InputStreamReader(response.getEntity()
			 * .getContent(), "UTF-8")); String json = reader.readLine();
			 * 
			 * String CheckStateDet = json.toString().replaceAll( "[\'\"]", "");
			 * if (CheckStateDet.equals("200")) { Log.v(TAG,
			 * "ADJUST_ADDITION_DETAILS**:" + CheckStateDet); ContentValues
			 * changeSyncStatefLoadDet = new ContentValues();
			 * changeSyncStatefLoadDet.put("adjDetSync", "1");
			 * mydb.update(ADJUST_ADDITION_DETAILS, changeSyncStatefLoadDet,
			 * "fadjdet_id ='" + FAdjAdditionDetIndex + "'", null); }
			 * 
			 * Log.e("json string", "test " + json.toString() + " lazim");
			 * System.out.println(json); } catch (Exception e) {
			 * e.printStackTrace(); } } arrayLength = 7; progressHandler
			 * .sendMessage(progressHandler.obtainMessage()); }
			 * 
			 * }
			 */
			// Upload stock order details

			if (selectOrderDetails != null) {
				if (selectOrderDetails.getCount() > 0) {
					while (selectOrderDetails.moveToNext()) {

						FStOrderDetIndex = selectOrderDetails.getString(0);
						String Amt = selectOrderDetails.getString(1);
						String BAmt = selectOrderDetails.getString(2);
						String BDisAmt = selectOrderDetails.getString(3);
						String BSellPrice = selectOrderDetails.getString(4);
						String BTSellPrice = selectOrderDetails.getString(5);
						String BTaxAmt = selectOrderDetails.getString(6);
						String BalQty = selectOrderDetails.getString(7);
						String CaseQty = selectOrderDetails.getString(8);
						String CostPrice = selectOrderDetails.getString(9);
						String DisAmt = selectOrderDetails.getString(10);
						String DisPer = selectOrderDetails.getString(11);
						String Itemcode = selectOrderDetails.getString(12);
						String PiceQty = selectOrderDetails.getString(13);
						String Qty = selectOrderDetails.getString(14);
						String ReaCode = selectOrderDetails.getString(15);
						String RecordId = selectOrderDetails.getString(16);
						String RefNo = selectOrderDetails.getString(17);
						String SellPrice = selectOrderDetails.getString(18);
						String SeqNo = selectOrderDetails.getString(19);
						String TSellPrice = selectOrderDetails.getString(20);
						String TaxAmt = selectOrderDetails.getString(21);
						String TxnType = selectOrderDetails.getString(22);
						String Txnseqno = selectOrderDetails.getString(23);
						String Type = selectOrderDetails.getString(24);
						String TxnDate = selectOrderDetails.getString(25);
						String itemdisper = selectOrderDetails.getString(27);
						String itemdisperval = selectOrderDetails.getString(28);

						double totlineItemDis = Double.parseDouble(BDisAmt
								.replaceAll("[,]", ""));
						double DisPerAmount = Double.parseDouble(itemdisperval
								.replaceAll("[,]", ""));
						double DisValueAmtCal = totlineItemDis - DisPerAmount;
						String DisValueAmtCalStr = Double
								.toString(DisValueAmtCal);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}

						// Upload record
						HttpPost request = new HttpPost(
								connectionURL
										+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/updateFOrddet");

						JSONStringer userJson = null;

						try {
							count = count + 1;
							Log.e("json", "Count:" + count);
							userJson = new JSONStringer()
									.object()
									.key("fODet")
									.object()
									.key("RefNo")
									.value(RefNo)
									.key("TxnDate")
									.value(TxnDate)
									.key("TxnType")
									.value(TxnType)
									.key("SeqNo")
									.value(SeqNo)
									.key("Itemcode")
									.value(Itemcode)
									.key("Txnseqno")
									.value(Txnseqno)
									.key("SellPrice")
									.value(SellPrice.replaceAll("[,]", ""))
									.key("BSellPrice")
									.value(BSellPrice.replaceAll("[,]", ""))
									.key("TSellPrice")
									.value(TSellPrice.replaceAll("[,]", ""))
									.key("BTSellPrice")
									.value(BTSellPrice.replaceAll("[,]", ""))
									.key("CostPrice")
									.value(CostPrice.replaceAll("[,]", ""))
									.key("CaseQty")
									.value(CaseQty)
									.key("Type")
									.value(Type)
									.key("PiceQty")
									.value(PiceQty.replaceAll("[,]", ""))
									.key("Qty")
									.value(Qty)
									.key("BalQty")
									.value(BalQty.replaceAll("[,]", ""))
									.key("DisPer")
									.value(DisPer)
									.key("DisAmt")
									.value(DisAmt.replaceAll("[,]", ""))
									.key("BDisAmt")
									.value(BDisAmt)
									.key("TaxAmt")
									.value(TaxAmt.replaceAll("[,]", ""))
									.key("BTaxAmt")
									.value(BTaxAmt.replaceAll("[,]", ""))
									.key("Amt")
									.value(Amt)
									.key("BAmt")
									.value(BAmt.replaceAll("[,]", ""))
									.key("ReaCode")
									.value(ReaCode)
									.key("DisPerAmt")
									.value(itemdisperval.replaceAll("[,]", ""))
									.key("DisValAmt")
									.value(DisValueAmtCalStr.replaceAll("[,]",
											"")).key("DbName")
									.value(currentUserServerDB).endObject();
							Log.e("json", "json created");
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						StringEntity entity = null;
						try {
							entity = new StringEntity(userJson.toString(),
									"UTF-8");
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						entity.setContentEncoding(new BasicHeader(
								HTTP.CONTENT_TYPE, "application/json"));
						entity.setContentType("application/json");

						request.setEntity(entity);

						// Send request to WCF service
						DefaultHttpClient httpClient = new DefaultHttpClient();

						try {
							Log.e("response", "connect");
							HttpResponse response = httpClient.execute(request);

							// ===========================================================
							HttpEntity entitye = response.getEntity();
							is = entity.getContent();
							if (is != null) {

								try {
									BufferedReader reader = new BufferedReader(
											new InputStreamReader(is,
													"iso-8859-1"), 8);
									sb = new StringBuilder();
									sb.append(reader.readLine() + "\n");
									String line = "0";
									while ((line = reader.readLine()) != null) {
										sb.append(line + "\n");
									}
									is.close();
									String result = sb.toString();
									Log.e("String Responce", "Print Responce:"
											+ result);
								} catch (Exception e1) {
									e1.printStackTrace();
								}
							}
							// ==================================
							Log.e(" ", "Res:" + response.toString());
							// System.out.println(response.toString());
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(response.getEntity()
											.getContent(), "UTF-8"));
							String json = reader.readLine();

							String CheckStateDet = json.toString().replaceAll(
									"[\'\"]", "");
							if (CheckStateDet.equals("200")) {
								ContentValues changeSyncStatefLoadDet = new ContentValues();
								changeSyncStatefLoadDet
										.put("storddetSync", "1");
								mydb.update(STOCK_ORDER_DETAIL,
										changeSyncStatefLoadDet, "stodet_id ='"
												+ FStOrderDetIndex + "'", null);
							}
							Log.e("json string", "test " + json.toString()
									+ " lazim");
							System.out.println(json);
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
					arrayLength = 13;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				}

			}
			arrayLength = 100;
			progressHandler.sendMessage(progressHandler.obtainMessage());
			// ----------_________----------_____________
			mydb.close();
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
			SynchDetails.dismiss();
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_InvoiceMenu.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("UPLOAD STATUS");
			// Setting Dialog Message
			alertDialog.setMessage("Uploading Data Completed...");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;

		}
	}

	protected void synchdata() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			mydb.execSQL("DROP TABLE IF EXISTS serverdb");
			// mydb.execSQL("DROP TABLE IF EXISTS FCompanySetting");
			// mydb.execSQL("DROP TABLE IF EXISTS FCompanyBranch");
			// mydb.execSQL("DROP TABLE IF EXISTS fControl");
			// mydb.execSQL("DROP TABLE IF EXISTS fSalRep");
			mydb.execSQL("DROP TABLE IF EXISTS fArea");
			// mydb.execSQL("DROP TABLE IF EXISTS fLocation");
			mydb.execSQL("DROP TABLE IF EXISTS fDebtor");
			// mydb.execSQL("DROP TABLE IF EXISTS fItemLoc");
			mydb.execSQL("DROP TABLE IF EXISTS fReason");
			mydb.execSQL("DROP TABLE IF EXISTS fItems");
			mydb.execSQL("DROP TABLE IF EXISTS fItemPri");
			mydb.execSQL("DROP TABLE IF EXISTS fBank");
			mydb.execSQL("DROP TABLE IF EXISTS fRoute");
			mydb.execSQL("DROP TABLE IF EXISTS fRouteDet");
			mydb.execSQL("DROP TABLE IF EXISTS fExpense");
			mydb.execSQL("DROP TABLE IF EXISTS fTown");
			mydb.execSQL("DROP TABLE IF EXISTS FMerch");
			mydb.execSQL("DROP TABLE IF EXISTS FSKU");

			mydb.execSQL("create table if not exists "
					+ SALES_DEALER
					+ "(_id integer primary key autoincrement,DealCode text not null,DealName text not null,DealAdd1 text not null,DealAdd2 text not null,DealAdd3 text not null,DealTele text not null,DealMob text not null,DealEMail text not null,Status text not null,Distance text not null,DealGdCode text not null,CusTypCode text not null,AddUser text not null,AddDate text not null,AddMach text not null,RecordId text not null);");

			mydb.execSQL("create table if not exists "
					+ YEARS_LIST
					+ "(year_id integer primary key autoincrement,yearname text not null);");

			mydb.execSQL("create table if not exists "
					+ MONTH_LIST
					+ "(month_id integer primary key autoincrement,monthindex text not null,monthname text not null);");

			mydb.execSQL("create table if not exists "
					+ SERVER_DETAILS
					+ "(server_id integer primary key autoincrement,serverurl text not null,portval text not null,serverdbname text not null,activeproperty text not null);");

			mydb.execSQL("create table if not exists "
					+ SERVER_DB_LIST
					+ "(sdb_id integer primary key autoincrement,sdbname text not null);");

			mydb.execSQL("create table if not exists "
					+ USER_SETTINGS
					+ "(_id integer primary key autoincrement,username text not null,lrepprefix text not null,lreploccode text not null,currentStOrdNo text not null,locationCode text not null,receiptCode text not null,serverDbName text not null,printerMac text not null,repareacode text not null,repdealcode text not null,reproutecode text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_AREA
					+ "(farea_id integer primary key autoincrement,AreaCode text not null,AreaName text not null,RegCode text not null,DealCode text not null,AddUser text not null,AddDatefarea text not null,AddMach text not null,RecordId text not null,timestamp_column text not null);");

			mydb.execSQL("create table if not exists "
					+ TEMP_REP_INVOICESUMERY
					+ "(remprepinv_id integer primary key autoincrement,repusername text not null,repprefix text not null,tempRepInvNoCode text not null,tempRepInvSerial text not null,invoiceComplete text not null,activeInvoice text not null,activeInvoiceValue text not null,activeInvItemDiscount text not null,activeInvCusDiscount text not null,activeInvCusDiscountValue text not null,InvoiceCustomerCode text not null,InvoiceCustomerName text not null,InvoiceSynchState text not null,recordDate text not null,recordSynchDate text not null,invlateststate text not null,activeInvoiceReturnValue text not null,activeInvoiceRemarks text not null,invoiceNoOfItems text not null,invoiceRef text not null,invoiceRefStl text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_LOCATION
					+ "(flocation_id integer primary key autoincrement,AddMach text not null,AddUser text not null,Address1 text not null,Address2 text not null,Address3 text not null,Contact text not null,EMail text not null,FaxNo text not null,LocCode text not null,LocName text not null,LoctCode text not null,RecordId text not null,RepCode text not null,TeleNo text not null,LocAddDate text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEMS
					+ "(_id integer primary key autoincrement,SKUCode text not null,ItemCode text not null,MapCode text not null,ItemName text not null,VenPcode text not null,GroupCode text not null,TypeCode text not null,TaxComCode text not null,UnitCode text not null,SkuSizCode text not null,ItemStatus text not null,ReOrderLvl text not null,ReOrderQty text not null,AvgPrice text not null,PurAcc text not null,PurRetAcc text not null,SVATAcc text not null,ExportAcc text not null,IndrExAcc text not null,SalAcc text not null,SalRetAcc text not null,DisAcc text not null,ClsStkAcc text not null,StkInAcc text not null,PrilCode text not null,BrandCode text not null,SBrandCode text not null,NOUCase text not null,OrdSeq text not null,AddUser text not null,AddDatefitem text not null,AddMach text not null,RecordId text not null,timestamp_column text not null,MustSale  text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_PRICE
					+ "(fitempri_id integer primary key autoincrement,SKUCode text not null,ItemCode text not null,PrilCode text not null,PriRDate text not null,Price text not null,AddUser text not null,AddDateIP text not null,AddMach text not null,Txnuser text not null,TxnDate text not null,TxnMach text not null,RecordId text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_LOC_DETAILS
					+ "(flocdet_id integer primary key autoincrement,LocCode text not null,ItemCode text not null,QOH text not null,RecordId text not null,timestamp_column text not null,syncRec text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_DEBTOR
					+ "(_id integer primary key autoincrement,DebCode text not null,DebName text not null,DebAdd1 text not null,DebAdd2 text not null,DebAdd3 text not null,DebTele text not null,DebMob text not null,DebEMail text not null,CretDate text not null,OutDis text not null,RemDis text not null,TownCode text not null,AreaCode text not null,DebCatCode text not null,DbGrCode text not null,DebClsCode text not null,Status text not null,DebLylty text not null,DealCode text not null,AddUser text not null,AddDateDEB text not null,AddMach text not null,RecordId text not null,timestamp_column text not null,CrdPeriod text not null,ChkCrdPrd text not null,CrdLimit text not null,ChkCrdLmt text not null,RepCode text not null,RankCode text not null,txndate text not null,TranBatch text not null,DebSumary text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_CONTROL
					+ "(fcontrol_id integer primary key autoincrement,ComName text not null,ComAdd1 text not null,ComAdd2 text not null,ComAdd3 text not null,comtel1 text not null,comtel2 text not null,comfax1 text not null,comemail text not null,comweb text not null,confyear text not null,contyear text not null,comRegNo text not null,ConfTxn text not null,ContTxn text not null,Crystalpath text not null,VatCmTaxNo text not null,NbtCmTaxNo text not null,SysId text not null,DealCode text not null,basecur text not null,BalgCrLm text not null,conage1 text not null,conage2 text not null,conage3 text not null,conage4 text not null,conage5 text not null,conage6 text not null,conage7 text not null,conage8 text not null,conage9 text not null,conage10 text not null,conage11 text not null,conage12 text not null,conage13 text not null,conage14 text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_COMPANY_SETTING
					+ "(fcomset_id integer primary key autoincrement,cSettingsCode text not null,cSettingGrp text not null,cLocationChar text not null,cCharVal text not null,nNumVal text not null,cRemarks text not null,nType text not null,bUpdateFlag text not null,cCompanyCode text not null,recordid text not null,timestamp_column text not null);");

			mydb.execSQL("create table if not exists "
					+ INV_DETAILS
					+ "(invdet_id integer primary key autoincrement,RefNo text not null,TxnDate text not null,TxnType text not null,SeqNo text not null,Itemcode text not null,Txnseqno text not null,SellPrice text not null,BSellPrice text not null,TSellPrice text not null,BTSellPrice text not null,CostPrice text not null,CaseQty text not null,Type text not null,PiceQty text not null,Qty text not null,BalQty text not null,DisPer text not null,DisAmt text not null,BDisAmt text not null,TaxAmt text not null,BTaxAmt text not null,Amt text not null,BAmt text not null,ReaCode text not null,Linkrec text not null,RecordId text not null,itemDescription text not null,refInvoiceDetNo text not null,refInvoiceDetCode text not null,refInvitemCaseQty text not null,refInvStockOrderNo text not null,invdetSync text not null,invsysdate text not null,itemdisper text not null,itemdisperval text not null,reasonCode  text not null,reasonDesc  text not null);");

			mydb.execSQL("create table if not exists "
					+ INV_HEADER
					+ "(invhead_id integer primary key autoincrement,RefNo text not null,RefNo1 text not null,InvType text not null,TxnDate text not null,ManuRef text not null,DealCode text not null,RepCode text not null,AreaCode text not null,RouteCode text not null,DebCode text not null,LocCode text not null,Remarks text not null,CostCode text not null,CurCode text not null,CurRate text not null,TxnType text not null,InvAmt text not null,OutDis text not null,InvDis text not null,TotMkrAmt text not null,UnOvAmt text not null,TotalDis text not null,TotalAmt text not null,AddUser text not null,AddDateInvHead text not null,AddMach text not null,prtcopy text not null,RecordId text not null,timestamp_column text not null,refInvoiceHeaderNo text not null,refInvoiceHeaderCode text not null,invhedSync text not null,outDisVal text not null);");

			mydb.execSQL("create table if not exists "
					+ SALES_REP_ROUTE
					+ "(route_id integer primary key autoincrement,RepCode text not null,RouteCode text not null,RouteName text not null,RecordId text not null,AddDate text not null,AreaCode text not null,DealCode text not null,FreqNo text not null,Km text not null,MinProcall text not null,RDAloRate text not null,RDTarget text not null,Remarks text not null,Status text not null,Tonnage text not null);");

			mydb.execSQL("create table if not exists "
					+ SALES_REP_ROUTEDET
					+ "(fRouteDet_id integer primary key autoincrement,RecordId text not null,DebCode text not null,RouteCode text not null);");

			mydb.execSQL("create table if not exists "
					+ BANK_DETAILS
					+ "(bankre_id integer primary key autoincrement,RecordId text not null,bankcode text not null,bankname text not null,bankaccno text not null,Branch text not null,bankadd1 text not null,bankadd2 text not null,AddDate text not null);");

			mydb.execSQL("create table if not exists "
					+ SALES_ORD_REASON
					+ "(freason_id integer primary key autoincrement,AddDate text not null,AddMach text not null,AddUser text not null,ReaCode text not null,ReaName text not null,ReaTcode text not null,RecordId text not null,Type text not null);");

			mydb.execSQL("create table if not exists "
					+ USER_EXPENSE
					+ "(uexp_id integer primary key autoincrement,ExpCode text not null,ExpGrpCode text not null,ExpName text not null,RecordId text not null,Status text not null,AddMach text not null,AddUser text not null);");

			mydb.execSQL("create table if not exists "
					+ TOWN_DETAILS
					+ "(townre_id integer primary key autoincrement,RecordId text not null,TownCode text not null,TownName text not null,DistrCode text not null,AddDate text not null,AddMach text not null,AddUser text not null);");

			mydb.execSQL("create table if not exists "
					+ MERCH_DETAILS
					+ "(merchre_id integer primary key autoincrement,RecordId text not null,MerchCode text not null,MerchName text not null,AddUser text not null,AddMach text not null,AddDate text not null);");

			// New Master Tables
			mydb.execSQL("create table if not exists "
					+ FTRGCAPUL
					+ "(ftrg_id integer primary key autoincrement,AddDate text not null,AddMach text not null,AddUser text not null,DealCode text not null,Month text not null,Qty text not null,RecordId text not null,RepCode text not null,SKUCode text not null,Year text not null);");

			mydb.execSQL("create table if not exists "
					+ FTYPE
					+ "(ftype_id integer primary key autoincrement,AddDate text not null,AddMach text not null,AddUser text not null,RecordId text not null,TypeCode text not null,TypeName text not null);");

			mydb.execSQL("create table if not exists "
					+ FSUBBRAND
					+ "(fsubbrand_id integer primary key autoincrement,AddDate text not null,AddMach text not null,AddUser text not null,RecordId text not null,SBrandCode text not null,SBrandName text not null);");

			mydb.execSQL("create table if not exists "
					+ FGROUP
					+ "(fgroup_id integer primary key autoincrement,AddDate text not null,AddMach text not null,AddUser text not null,GroupCode text not null,GroupName text not null,RecordId text not null);");

			mydb.execSQL("create table if not exists "
					+ FSKU
					+ "(fsku_id integer primary key autoincrement,AddDate text not null,AddMach text not null,AddUser text not null,BrandCode text not null,GroupCode text not null,ItemStatus text not null,MustSale text not null,NOUCase text not null,OrdSeq text not null,RecordId text not null,SBrandCode text not null,SKUCode text not null,SkuName text not null,SkuSizCode text not null,Tonnage text not null,TypeCode text not null,Unit text not null);");

			mydb.execSQL("create table if not exists "
					+ FBRAND
					+ "(fbrand_id integer primary key autoincrement,AddMach text not null,AddUser text not null,BrandCode text not null,BrandName text not null,RecordId text not null);");

			// Stock Orders
			mydb.execSQL("create table if not exists "
					+ STOCK_ORDER_INVOICESUMERY
					+ "(remprepinv_id integer primary key autoincrement,repusername text not null,repprefix text not null,tempRepInvNoCode text not null,tempRepInvSerial text not null,invoiceComplete text not null,activeInvoice text not null,activeInvoiceValue text not null,activeInvItemDiscount text not null,activeInvCusDiscount text not null,activeInvCusDiscountValue text not null,InvoiceCustomerCode text not null,InvoiceCustomerName text not null,InvoiceSynchState text not null,recordDate text not null,recordSynchDate text not null,invlateststate text not null,activeInvoiceReturnValue text not null,activeInvoiceRemarks text not null,invoiceNoOfItems text not null,invoiceRef text not null,invoiceRefStl text not null,invoicedelidate text not null,invManuRefNo text not null);");

			mydb.execSQL("create table if not exists "
					+ STOCK_ORDER_HEAD
					+ "(stohed_id integer primary key autoincrement,AddMach text not null,AddUser text not null,AreaCode text not null,CostCode text not null,CurCode text not null,CurRate text not null,DealCode text not null,DebCode text not null,InvAmt text not null,InvDis text not null,InvFlg text not null,LocCode text not null,ManuRef text not null,OutDis text not null,RecordId text not null,RefNo text not null,Remarks text not null,RepCode text not null,RouteCode text not null,TotMkrAmt text not null,TotalAmt text not null,TotalDis text not null,TranBatch text not null,TxnType text not null,UnOvAmt text not null,prtcopy text not null,TxnDate text not null,stOrderComplete text not null,stordhedSync text not null,outDisVal text not null,ohAddDate text not null,delvDate text not null);");

			mydb.execSQL("create table if not exists "
					+ STOCK_ORDER_DETAIL
					+ "(stodet_id integer primary key autoincrement,Amt text not null,BAmt text not null,BDisAmt text not null,BSellPrice text not null,BTSellPrice text not null,BTaxAmt text not null,BalQty text not null,CaseQty text not null,CostPrice text not null,DisAmt text not null,DisPer text not null,Itemcode text not null,PiceQty text not null,Qty text not null,ReaCode text not null,RecordId text not null,RefNo text not null,SellPrice text not null,SeqNo text not null,TSellPrice text not null,TaxAmt text not null,TxnType text not null,Txnseqno text not null,Type text not null,TxnDate text not null,storddetSync text not null,itemdisper text not null,itemdisperval text not null,reasonDesc text not null,odAddDate text not null);");

			mydb.execSQL("create table if not exists "
					+ TEMPSTOCK_ORDER_DETAIL
					+ "(invdet_id integer primary key autoincrement,RefNo text not null,TxnDate text not null,TxnType text not null,SeqNo text not null,Itemcode text not null,Txnseqno text not null,SellPrice text not null,BSellPrice text not null,TSellPrice text not null,BTSellPrice text not null,CostPrice text not null,CaseQty text not null,Type text not null,PiceQty text not null,Qty text not null,BalQty text not null,DisPer text not null,DisAmt text not null,BDisAmt text not null,TaxAmt text not null,BTaxAmt text not null,Amt text not null,BAmt text not null,ReaCode text not null,Linkrec text not null,RecordId text not null,itemDescription text not null,refInvoiceDetNo text not null,refInvoiceDetCode text not null,refInvitemCaseQty text not null,refInvStockOrderNo text not null,refReasondetails text not null,itemdisper text not null,itemdisperval text not null,odtAddDate text not null);");

			mydb.execSQL("create table if not exists "
					+ TEMPSTOCK_ORDER_HEAD
					+ "(invhead_id integer primary key autoincrement,RefNo text not null,RefNo1 text not null,InvType text not null,TxnDate text not null,ManuRef text not null,DealCode text not null,RepCode text not null,AreaCode text not null,RouteCode text not null,DebCode text not null,LocCode text not null,Remarks text not null,CostCode text not null,CurCode text not null,CurRate text not null,TxnType text not null,InvAmt text not null,OutDis text not null,InvDis text not null,TotMkrAmt text not null,UnOvAmt text not null,TotalDis text not null,TotalAmt text not null,AddUser text not null,AddDateInvHead text not null,AddMach text not null,prtcopy text not null,RecordId text not null,timestamp_column text not null,refInvoiceHeaderNo text not null,refInvoiceHeaderCode text not null);");

			// Stock Loading
			mydb.execSQL("create table if not exists "
					+ STOCK_LOAD_HEAD
					+ "(RecordId integer primary key autoincrement,RefNo text not null,TxnDate text not null,ManuRef text not null,CostCode text not null,Remarks text not null,TxnType text not null,TotalAmt text not null,DelPersn text not null,DelAdd1 text not null,DelAdd2 text not null,DelAdd3 text not null,VehicalNo text not null,GlPost text not null,GlBatch text not null,AddUser text not null,AddDatestlh text not null,AddMach text not null,TranFlg text not null,ItemType text not null,stlhedSync text not null);");

			mydb.execSQL("create table if not exists "
					+ STOCK_LOAD_DETAIL
					+ "(RecordId integer primary key autoincrement,RefNo text not null,TxnDate text not null,LocCode text not null,TxnType text not null,SeqNo text not null,ItemCode text not null,CaseQty text not null,PiceQty text not null,Qty text not null,CostPrice text not null,Amt text not null,RecordDate text not null,RecordChecked text not null,LitemName text not null,LitemQOH text not null,CaseUnits text not null,stldetSync text not null);");

			mydb.execSQL("create table if not exists "
					+ TEMP_STOCK_LOADING_SUMMARY
					+ "(temprepStLoad_id integer primary key autoincrement,stlrepusername text not null,stlrepprefix text not null,tempRepStLoadCode text not null,tempRepStLoadSerial text not null,tempRepStLoadRefNo text not null,stLoadComplete text not null,stLoadActive text not null,stLoadActiveValue text not null,stLoadstartDate text not null,fromLocName text not null,toLocName text not null);");

			mydb.execSQL("create table if not exists "
					+ INV_COMPANY_BRANCH
					+ "(fcombra_id integer primary key autoincrement,BranchCode text not null,RecordId text not null,cSettingsCode text not null,nNumVal text not null);");

			mydb.execSQL("create table if not exists "
					+ INV_SAL_REP
					+ "(fsalrep_id integer primary key autoincrement,ASECode text not null,AreaCode text not null,DealCode text not null,RecordId text not null,RepCode text not null,RepPrefix text not null,RepTCode text not null,repPhoneNo text not null);");

			// Stock UnLoading
			mydb.execSQL("create table if not exists "
					+ STOCK_LOAD_HEADUN
					+ "(RecordId integer primary key autoincrement,RefNo text not null,TxnDate text not null,ManuRef text not null,CostCode text not null,Remarks text not null,TxnType text not null,TotalAmt text not null,DelPersn text not null,DelAdd1 text not null,DelAdd2 text not null,DelAdd3 text not null,VehicalNo text not null,GlPost text not null,GlBatch text not null,AddUser text not null,AddDatestlh text not null,AddMach text not null,TranFlg text not null,ItemType text not null,stlhedunSync text not null,IntangFlg text not null);");

			mydb.execSQL("create table if not exists "
					+ STOCK_LOAD_DETAILUN
					+ "(RecordId integer primary key autoincrement,RefNo text not null,TxnDate text not null,LocCode text not null,TxnType text not null,SeqNo text not null,ItemCode text not null,CaseQty text not null,PiceQty text not null,Qty text not null,CostPrice text not null,Amt text not null,RecordDate text not null,RecordChecked text not null,LitemName text not null,LitemQOH text not null,CaseUnits text not null,stldetunSync text not null,IntangFlg text not null);");

			mydb.execSQL("create table if not exists "
					+ TEMP_STOCK_LOADING_SUMMARYUN
					+ "(temprepStLoad_id integer primary key autoincrement,stlrepusername text not null,stlrepprefix text not null,tempRepStLoadCode text not null,tempRepStLoadSerial text not null,tempRepStLoadRefNo text not null,stLoadComplete text not null,stLoadActive text not null,stLoadActiveValue text not null,stLoadstartDate text not null,fromLocName text not null,toLocName text not null);");

			// Stock Damage
			mydb.execSQL("create table if not exists "
					+ STOCK_LOAD_HEADDAM
					+ "(RecordId integer primary key autoincrement,RefNo text not null,TxnDate text not null,ManuRef text not null,DealCode text not null,Remarks text not null,TxnType text not null,TotalAmt text not null,CostCode text not null,ReaCode text not null,GlPost text not null,GlBatch text not null,AddUser text not null,AddDatestlh text not null,AddMach text not null,ItemType text not null,stldmhedSync text not null);");

			mydb.execSQL("create table if not exists "
					+ STOCK_LOAD_DETAILDAM
					+ "(RecordId integer primary key autoincrement,RefNo text not null,TxnDate text not null,LocCode text not null,TxnType text not null,SeqNo text not null,ItemCode text not null,CaseQty text not null,PiceQty text not null,Qty text not null,CostPrice text not null,Amt text not null,RecordDate text not null,RecordChecked text not null,LitemName text not null,LitemQOH text not null,CaseUnits text not null,reaCode text not null,stldmdetSync text not null);");

			mydb.execSQL("create table if not exists "
					+ TEMP_STOCK_LOADING_SUMMARYDAM
					+ "(temprepStLoad_id integer primary key autoincrement,stlrepusername text not null,stlrepprefix text not null,tempRepStLoadCode text not null,tempRepStLoadSerial text not null,tempRepStLoadRefNo text not null,stLoadComplete text not null,stLoadActive text not null,stLoadActiveValue text not null,stLoadstartDate text not null,fromLocName text not null,toLocName text not null);");

			// Cash / Cheque Receipt
			mydb.execSQL("create table if not exists "
					+ TEMP_RECEIPT_SUMMARY
					+ "(tempReceipt_id integer primary key autoincrement,treceiptusername text not null,treceiptprefix text not null,treceiptCode text not null,treceiptSerial text not null,treceiptRefNo text not null,treceiptComplete text not null,treceiptActive text not null,treceiptManualno text not null,treceiptstartDate text not null,treceiptCusno text not null,treceiptCusName text not null,treceiptPayType text not null,treceiptChequeno text not null,treceiptChequeDate text not null,treceiptBankNo text not null,treceiptBankName text not null,treceiptReceiptAmt text not null,treceiptReceiptBalAmt text not null,treceiptRemark text not null);");

			mydb.execSQL("create table if not exists "
					+ RECEIPT_HEADER
					+ "(reched_id integer primary key autoincrement,RefNo text not null,ManuRef text not null,SaleRefNo text not null,RepCode text not null,TxnType text not null,Chqno text not null,ChqDate text not null,TxnDate text not null,CurCode text not null,CurRate text not null,DebCode text not null,TotalAmt text not null,BTotalAmt text not null,BankCur text not null,BankRate text not null,BankAmt text not null,BankCharge text not null,BBankChg text not null,GnLsCal text not null,DbAcc text not null,PayType text not null,PrtCopy text not null,GlPost text not null,Remarks text not null,CardSlipNo text not null,ExpDate text not null,CrdTypCode text not null,CCBankAmt text not null,GlBatch text not null,AddUser text not null,AddMach text not null,AddrecDate text not null,recipthedSync text not null);");

			mydb.execSQL("create table if not exists "
					+ RECEIPT_DETAILS
					+ "(RecDet_id integer primary key autoincrement,RefNo text not null,RefNo1 text not null,SaleRefNo text not null,ManuRef text not null,TxnType text not null,TxnDate text not null,DtxnDate text not null,DtxnType text not null,DCurCode text not null,DCurRate text not null,OCurRate text not null,RepCode text not null,Amt text not null,BAmt text not null,GainLosAmt text not null,BnkChgs text not null,BBnkChgs text not null,AloAmt text not null,OvPayAmt text not null,OvPayBal text not null,reciptdetSync text not null,recsysdate text not null);");

			mydb.execSQL("create table if not exists "
					+ RECEIPT_INVOICES
					+ "(recinv_id integer primary key autoincrement,RecordId text not null,RefNo text not null,RefInv text not null,SaleRefNo text not null,ManuRef text not null,TxnType	text not null,TxnDate text not null,CurCode text not null,CurRate text not null,DebCode text not null,RepCode text not null,TaxComCode text not null,TaxAmt text not null,BTaxAmt text not null,Amt text not null,BAmt text not null,TotBal text not null,TotBal1 text not null,OvPayAmt text not null,Remarks text not null,CrAcc text not null,PrtCopy text not null,GlPost text not null,glbatch text not null,AddUser text not null,AddDate	text not null,AddMach	text not null,RefNo1	text not null);");

			// Adjustment
			mydb.execSQL("create table if not exists "
					+ TEMP_ADJUSTMENT_SUMMARY
					+ "(adjustsum_id integer primary key autoincrement,username text not null,refCode text not null,refSerial text not null,currentState text not null,activeMode text not null,LocCode text not null,LocName text not null,TotalAmount text not null,ManuRefNo text not null,AdjustTxnType text not null);");

			mydb.execSQL("create table if not exists "
					+ ADJUST_ADDITION_DETAILS
					+ "(fadjdet_id integer primary key autoincrement,RefNo text not null,TxnDate text not null,TxnType text not null,SeqNo text not null,ItemCode text not null,CaseQty text not null,PiceQty text not null,Qty text not null,CostPrice text not null,Amt text not null,ReaCode text not null,ItemName text not null,QOH text not null,ReaName text not null,CaseUnits text not null,CasePrice text not null,adjDetSync text not null);");

			mydb.execSQL("create table if not exists "
					+ ADJUST_ADDITION_HEADER
					+ "(fadjhed_id integer primary key autoincrement,RefNo text not null,TxnDate text not null,CostCode text not null,ManuRef text not null,DealCode text not null,RefNo2 text not null,TxnType text not null,TotalAmt text not null,Remarks text not null,LocCode text not null,ReaCode text not null,GlPost text not null,GlBatch text not null,AddUser text not null,AddDate text not null,AddMach text not null,ItemType text not null,adjHedSync text not null);");

			// Day Expence
			mydb.execSQL("create table if not exists "
					+ TEMP_DAYEXPENSE_SUMMARY
					+ "(dexpsum_id integer primary key autoincrement,dexprepusername text not null,dexprepprefix text not null,dexprefcode text not null,dexprefnoserial text not null,dexpreComplete text not null,dexpreActive text not null,dexprefnocode text not null,dexpremark text not null,amountTot text not null);");

			mydb.execSQL("create table if not exists "
					+ DAYEXPENSE_HEADER
					+ "(dexphed_id integer primary key autoincrement,RefNo text not null,TxnDate text not null,RepName text not null,DealCode text not null,CostCode text not null,RepCode text not null,RegCode text not null,AreaCode text not null,Remarks text not null,AddUser text not null,AddDate text not null,AddMach text not null,TranBatch text not null);");

			mydb.execSQL("create table if not exists "
					+ DAYEXPENSE_DETAILS
					+ "(sdb_id integer primary key autoincrement,RefNo text not null,TxnDate text not null,SeqNo text not null,ExpCode text not null,Amt text not null,ExpName text not null);");

			// None Productive Calls
			mydb.execSQL("create table if not exists "
					+ DAILY_NONE_PRDCALLS_HEAD
					+ "(RecordId integer primary key autoincrement,RefNo text not null,TxnDate text not null,DebCode text not null,DebName text not null,Status text not null,stldmhedSync text not null,Reason text not null);");

		} catch (Exception e) {
		}
		mydb.close();
		new DownloadAdministrative().execute();

	}

	// Synch - Uploading Data Dialog Box Handling function
	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_SYNC_DATA:
			LayoutInflater inflater = LayoutInflater.from(this);
			View dialogview = inflater.inflate(R.layout.dm_dialog_synch, null);

			AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
			dialogbuilder.setTitle("Select Option...");
			dialogbuilder.setView(dialogview);
			SynchDetails = dialogbuilder.create();

			break;

		case DIALOG_SYNC_STOCKS:
			LayoutInflater inflaterst = LayoutInflater.from(this);
			View dialogviewst = inflaterst.inflate(
					R.layout.dm_dialog_synch_stocks, null);
			AlertDialog.Builder dialogbuilderst = new AlertDialog.Builder(this);
			dialogbuilderst.setTitle("Select Option...");
			dialogbuilderst.setView(dialogviewst);
			SynchDetails = dialogbuilderst.create();
			break;

		case DIALOG_UPLOADING_DATA:
			LayoutInflater inflateru = LayoutInflater.from(this);
			View dialogviewu = inflateru.inflate(R.layout.dm_dialog_uploading,
					null);
			AlertDialog.Builder dialogbuilderu = new AlertDialog.Builder(this);
			dialogbuilderu.setTitle("Select Option...");
			dialogbuilderu.setView(dialogviewu);
			SynchDetails = dialogbuilderu.create();
			break;

		case DIALOG_REUPLOADING_DATA:
			LayoutInflater inflaterur = LayoutInflater.from(this);
			View dialogviewur = inflaterur.inflate(
					R.layout.dm_dialog_reuploading, null);
			AlertDialog.Builder dialogbuilderur = new AlertDialog.Builder(this);
			dialogbuilderur.setTitle("Select Uploading Option...");
			dialogbuilderur.setView(dialogviewur);
			SynchDetails = dialogbuilderur.create();
			break;

		case DIALOG_SYNC_SUCCESS:
			LayoutInflater inflaters = LayoutInflater.from(this);
			View dialogviews = inflaters.inflate(
					R.layout.dm_dialog_sync_success, null);
			AlertDialog.Builder dialogbuilders = new AlertDialog.Builder(this);
			dialogbuilders.setTitle("Sync Data Completed. Select SalesRef...");
			dialogbuilders.setView(dialogviews);
			SynchDetails = dialogbuilders.create();
			break;

		case DIALOG_DOWNLOAD_STOCKS:
			LayoutInflater inflaterdown = LayoutInflater.from(this);
			View dialogviewsdown = inflaterdown.inflate(
					R.layout.dm_dialog_validate_download, null);
			AlertDialog.Builder dialogbuildersdown = new AlertDialog.Builder(
					this);
			dialogbuildersdown.setTitle("DOWNLOAD STOCKS");
			dialogbuildersdown
					.setMessage("Invoice Details Upload Incomplete.Are Sure You Want To Proceed...");
			dialogbuildersdown.setView(dialogviewsdown);
			SynchDetails = dialogbuildersdown.create();
			break;

		}
		return SynchDetails;
	}

	// DownloadJSON AsyncTask
	private class DownloadAdministrative extends AsyncTask<Void, Void, Void> {

		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(DM_InvoiceMenu.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Downloading Details");
			// Set progressdialog message
			mProgressDialog.setMessage("Loading Details...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		// *****************Background Process**************************
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub

			// *****************Download Available Data Bases**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/GetdatabaseNames/mobile123");
				URLConnection jc = json.openConnection();
				BufferedReader readerfdblist = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfdblist.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArray = jsonResponse
						.getJSONArray("GetdatabaseNamesResult");
				Log.v(TAG, "Array Length Server DB :" + jsonArray.length());

				for (int i = 0; i < jsonArray.length(); i++) {
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
					JSONObject jObject = (JSONObject) jsonArray.get(i);
					String sdbname = jObject.getString("Name");
					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowdblist = new ContentValues();
					Cursor sdblistrows = null;
					try {
						sdblistrows = mydb.query(SERVER_DB_LIST, null,
								"sdbname ='" + sdbname + "'", null, null, null,
								null);
					} catch (Exception e) {
					}
					if (sdblistrows != null) {
						if (sdblistrows.getCount() >= 1) {
							while (sdblistrows.moveToNext()) {
								Log.v(TAG, "Excisting fServer DB 1 :" + sdbname);
							}
						} else {
							Log.v(TAG, "DB 1:" + sdbname.trim());
							newrowdblist.put("sdbname", sdbname.trim());
							mydb.insert(SERVER_DB_LIST, null, newrowdblist);
							sdblistrows.close();
							mydb.close();
						}
					}
					mydb.close();
				}
				arrayLength = 3;
				Log.v(TAG, "arrayLength : " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfdblist.close();

			} catch (Exception e) {
			}
			// ******Download Available fItemLoc details**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL jsonfItemLoc = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fItemLoc/mobile123"
								+ "/" + serverDbName);
				URLConnection jcfItemLoc = jsonfItemLoc.openConnection();
				BufferedReader readerfItemLoc = new BufferedReader(
						new InputStreamReader(jcfItemLoc.getInputStream()));

				String linefItemLoc = readerfItemLoc.readLine();

				JSONObject jsonResponsefItemLoc = new JSONObject(linefItemLoc);

				JSONArray jsonArrayfItemLoc = jsonResponsefItemLoc
						.getJSONArray("fItemLocResult");
				Log.v(TAG,
						"Array Length fItemLoc :" + jsonArrayfItemLoc.length());
				for (int i = 0; i < jsonArrayfItemLoc.length(); i++) {
					JSONObject jObjectfItemLoc = (JSONObject) jsonArrayfItemLoc
							.get(i);
					String ItemCodeFI = jObjectfItemLoc.getString("ItemCode");
					String LocCodeFI = jObjectfItemLoc.getString("LocCode");
					String QOHFI = jObjectfItemLoc.getString("QOH");
					RecordIdFI = jObjectfItemLoc.getString("RecordId");
					RecordIdFI = RecordIdFI.trim();
					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfItemLoc = new ContentValues();
					Cursor fItemLocrows = null;
					try {
						String queryfil = "SELECT LocCode,RecordId from fItemLoc Where RecordId ='"
								+ RecordIdFI + "'";
						fItemLocrows = mydb.rawQuery(queryfil, null);
					} catch (Exception e) {
					}
					if (fItemLocrows != null) {
						if (fItemLocrows.getCount() >= 1) {
							while (fItemLocrows.moveToNext()) {
								Log.v(TAG, "Excisting fItemLocrows 1 :"
										+ RecordIdFI);
								String chkLocCode = fItemLocrows.getString(0);
								String chkRecordId = fItemLocrows.getString(1);

								if (chkLocCode.equals("MS")) {
									Log.v(TAG, "Update fItemLoc QOH: "
											+ chkRecordId);
									newrowfItemLoc.put("QOH", QOHFI.trim());
									mydb.update(ITEM_LOC_DETAILS,
											newrowfItemLoc, "RecordId ='"
													+ chkRecordId + "'", null);
								}
							}
						} else {
							Log.v(TAG, "fItemLoc 1:" + RecordIdFI);
							newrowfItemLoc.put("LocCode", LocCodeFI.trim());
							newrowfItemLoc.put("ItemCode", ItemCodeFI.trim());
							newrowfItemLoc.put("QOH", QOHFI.trim());
							newrowfItemLoc.put("RecordId", RecordIdFI);
							newrowfItemLoc.put("timestamp_column",
									getCurrentTimeString().toString());
							newrowfItemLoc.put("syncRec", "0");
							mydb.insert(ITEM_LOC_DETAILS, null, newrowfItemLoc);
							fItemLocrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 1: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfItemLoc.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download fItemPri**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fItemPri/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfItemPri = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfItemPri.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfItemPri = jsonResponse
						.getJSONArray("fItemPriResult");
				Log.v(TAG,
						"Array Length fItemPri :" + jsonArrayfItemPri.length());
				for (int i = 0; i < jsonArrayfItemPri.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArrayfItemPri.get(i);
					String SKUCode = jObject.getString("SKUCode");
					String ItemCode = jObject.getString("ItemCode");
					String PrilCode = jObject.getString("PrilCode");
					String Price = jObject.getString("Price");
					String AddUser = jObject.getString("AddUser");
					String AddMach = jObject.getString("AddMach");
					String Txnuser = jObject.getString("Txnuser");
					String TxnMach = jObject.getString("TxnMach");
					String RecordId = jObject.getString("RecordId");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfItemPri = new ContentValues();
					Cursor newrowfItemPriuserrows = null;
					try {
						newrowfItemPriuserrows = mydb.query(ITEM_PRICE, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (newrowfItemPriuserrows != null) {
						if (newrowfItemPriuserrows.getCount() >= 1) {
							Log.v(TAG, "Excisting newrowfItemPriuserrows 2");
						} else {
							Log.v(TAG, "fItemPri 2:" + RecordId.trim());
							newrowfItemPri.put("SKUCode", SKUCode.trim());
							newrowfItemPri.put("ItemCode", ItemCode.trim());
							newrowfItemPri.put("PrilCode", PrilCode.trim());
							newrowfItemPri.put("PriRDate",
									getCurrentTimeString().toString());
							newrowfItemPri.put("Price", Price.trim());
							newrowfItemPri.put("AddUser", AddUser.trim());
							newrowfItemPri.put("AddDateIP",
									getCurrentTimeString().toString());
							newrowfItemPri.put("AddMach", AddMach.trim());
							newrowfItemPri.put("Txnuser", Txnuser.trim());
							newrowfItemPri.put("TxnDate",
									getCurrentTimeString().toString());
							newrowfItemPri.put("TxnMach", TxnMach.trim());
							newrowfItemPri.put("RecordId", RecordId.trim());
							mydb.insert(ITEM_PRICE, null, newrowfItemPri);
							newrowfItemPriuserrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 2: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfItemPri.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download fItems**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fItems/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfItems = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfItems.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfItems = jsonResponse
						.getJSONArray("fItemsResult");
				Log.v(TAG, "Array Length fItems :" + jsonArrayfItems.length());
				for (int i = 0; i < jsonArrayfItems.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfItems.get(i);
					String SKUCode = jObject.getString("SKUCode");
					String ItemCode = jObject.getString("ItemCode");
					String MapCode = jObject.getString("MapCode");
					String ItemName = jObject.getString("ItemName");
					String VenPcode = jObject.getString("VenPcode");
					String GroupCode = jObject.getString("GroupCode");
					String TypeCode = jObject.getString("TypeCode");
					String TaxComCode = jObject.getString("TaxComCode");
					String UnitCode = jObject.getString("UnitCode");
					String SkuSizCode = jObject.getString("SkuSizCode");
					String ItemStatus = jObject.getString("ItemStatus");
					String ReOrderLvl = jObject.getString("ReOrderLvl");
					String ReOrderQty = jObject.getString("ReOrderQty");
					String AvgPrice = jObject.getString("AvgPrice");
					String PurAcc = jObject.getString("PurAcc");
					String PurRetAcc = jObject.getString("PurRetAcc");
					String SVATAcc = jObject.getString("SVATAcc");
					String ExportAcc = jObject.getString("ExportAcc");
					String IndrExAcc = jObject.getString("IndrExAcc");
					String SalAcc = jObject.getString("SalAcc");
					String SalRetAcc = jObject.getString("SalRetAcc");
					String DisAcc = jObject.getString("DisAcc");
					String ClsStkAcc = jObject.getString("ClsStkAcc");
					String StkInAcc = jObject.getString("StkInAcc");
					String PrilCode = jObject.getString("PrilCode");
					String BrandCode = jObject.getString("BrandCode");
					String SBrandCode = jObject.getString("SBrandCode");
					String NOUCase = jObject.getString("NOUCase");
					String OrdSeq = jObject.getString("OrdSeq");
					String AddUser = jObject.getString("AddUser");
					String AddMach = jObject.getString("AddMach");
					String RecordId = jObject.getString("RecordId");
					String MustSale = jObject.getString("MustSale");
					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfItems = new ContentValues();
					Cursor newrowfItemListuserrows = null;
					try {
						newrowfItemListuserrows = mydb.query(ITEMS, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (newrowfItemListuserrows != null) {
						if (newrowfItemListuserrows.getCount() >= 1) {
							Log.v(TAG, "Excisting newrowfItemListuserrows 3");
						} else {

							Log.v(TAG, "fItems 3:" + RecordId.trim());
							newrowfItems.put("SKUCode", SKUCode.trim());
							newrowfItems.put("ItemCode", ItemCode.trim());
							newrowfItems.put("MapCode", MapCode.trim());
							newrowfItems.put("ItemName", ItemName.trim());
							newrowfItems.put("VenPcode", VenPcode.trim());
							newrowfItems.put("GroupCode", GroupCode.trim());
							newrowfItems.put("TypeCode", TypeCode.trim());
							newrowfItems.put("TaxComCode", TaxComCode.trim());
							newrowfItems.put("UnitCode", UnitCode.trim());
							newrowfItems.put("SkuSizCode", SkuSizCode.trim());
							newrowfItems.put("ItemStatus", ItemStatus.trim());
							newrowfItems.put("ReOrderLvl", ReOrderLvl.trim());
							newrowfItems.put("ReOrderQty", ReOrderQty.trim());
							newrowfItems.put("AvgPrice", AvgPrice.trim());
							newrowfItems.put("PurAcc", PurAcc.trim());
							newrowfItems.put("PurRetAcc", PurRetAcc.trim());
							newrowfItems.put("SVATAcc", SVATAcc.trim());
							newrowfItems.put("ExportAcc", ExportAcc.trim());
							newrowfItems.put("IndrExAcc", IndrExAcc.trim());
							newrowfItems.put("SalAcc", SalAcc.trim());
							newrowfItems.put("SalRetAcc", SalRetAcc.trim());
							newrowfItems.put("DisAcc", DisAcc.trim());
							newrowfItems.put("ClsStkAcc", ClsStkAcc.trim());
							newrowfItems.put("StkInAcc", StkInAcc.trim());
							newrowfItems.put("PrilCode", PrilCode.trim());
							newrowfItems.put("BrandCode", BrandCode.trim());
							newrowfItems.put("SBrandCode", SBrandCode.trim());
							newrowfItems.put("NOUCase", NOUCase.trim());
							if (OrdSeq.length() == 1) {
								OrdSeq = "0" + OrdSeq;
							}
							newrowfItems.put("OrdSeq", OrdSeq.trim());
							newrowfItems.put("AddUser", AddUser.trim());
							newrowfItems.put("AddDatefitem",
									getCurrentTimeString().toString());
							newrowfItems.put("AddMach", AddMach.trim());
							newrowfItems.put("RecordId", RecordId.trim());
							newrowfItems.put("timestamp_column ",
									getCurrentTimeString().toString());
							newrowfItems.put("MustSale ", MustSale.trim());
							mydb.insert(ITEMS, null, newrowfItems);
							newrowfItemListuserrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 3: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfItems.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download Fdebtor**************

			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/Fdebtor/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerFdebtor = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerFdebtor.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayFdebtor = jsonResponse
						.getJSONArray("FdebtorResult");
				Log.v(TAG, "Array Length Fdebtor :" + jsonArrayFdebtor.length());
				for (int i = 0; i < jsonArrayFdebtor.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayFdebtor.get(i);
					String DebCode = jObject.getString("DebCode");
					String DebName = jObject.getString("DebName");
					String DebAdd1 = jObject.getString("DebAdd1");
					String DebAdd2 = jObject.getString("DebAdd2");
					String DebAdd3 = jObject.getString("DebAdd3");
					String DebTele = jObject.getString("DebTele");
					String DebMob = jObject.getString("DebMob");
					String DebEMail = jObject.getString("DebEMail");
					String OutDis = jObject.getString("OutDis");
					String RemDis = jObject.getString("RemDis");
					String TownCode = jObject.getString("TownCode");
					String AreaCode = jObject.getString("AreaCode");
					String DebCatCode = jObject.getString("DebCatCode");
					String DbGrCode = jObject.getString("DbGrCode");
					String DebClsCode = jObject.getString("DebClsCode");
					String Status = jObject.getString("Status");
					String DebLylty = jObject.getString("DebLylty");
					String DealCode = jObject.getString("DealCode");
					String AddUser = jObject.getString("AddUser");
					String AddMach = jObject.getString("AddMach");
					String RecordId = jObject.getString("RecordId");
					String CrdPeriod = jObject.getString("CrdPeriod");
					String ChkCrdPrd = jObject.getString("ChkCrdPrd");
					String CrdLimit = jObject.getString("CrdLimit");
					String ChkCrdLmt = jObject.getString("ChkCrdLmt");
					String RepCode = jObject.getString("RepCode");
					String RankCode = jObject.getString("RankCode");
					String TranBatch = jObject.getString("TranBatch");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfdebtord = new ContentValues();
					Cursor fdebtorduserrows = null;
					try {
						fdebtorduserrows = mydb.query(ITEM_DEBTOR, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (fdebtorduserrows != null) {
						if (fdebtorduserrows.getCount() >= 1) {
							Log.v(TAG, "Excisting fdebtorduserrows 4");
						} else {
							Log.v(TAG, "Fdebtor 4:" + RecordId.trim());
							newrowfdebtord.put("DebCode", DebCode.trim());
							newrowfdebtord.put("DebName", DebName.trim());
							newrowfdebtord.put("DebAdd1", DebAdd1.trim());
							newrowfdebtord.put("DebAdd2", DebAdd2.trim());
							newrowfdebtord.put("DebAdd3", DebAdd3.trim());
							newrowfdebtord.put("DebTele", DebTele.trim());
							newrowfdebtord.put("DebMob", DebMob.trim());
							newrowfdebtord.put("DebEMail", DebEMail.trim());
							newrowfdebtord.put("CretDate",
									getCurrentTimeString().toString());
							newrowfdebtord.put("OutDis", OutDis.trim());
							newrowfdebtord.put("RemDis", RemDis.trim());
							newrowfdebtord.put("TownCode", TownCode.trim());
							newrowfdebtord.put("AreaCode", AreaCode.trim());
							newrowfdebtord.put("DebCatCode", DebCatCode.trim());
							newrowfdebtord.put("DbGrCode", DbGrCode.trim());
							newrowfdebtord.put("DebClsCode", DebClsCode.trim());
							newrowfdebtord.put("Status", Status.trim());
							newrowfdebtord.put("DebLylty", DebLylty.trim());
							newrowfdebtord.put("DealCode", DealCode.trim());
							newrowfdebtord.put("AddUser", AddUser.trim());
							newrowfdebtord.put("AddDateDEB",
									getCurrentTimeString().toString());
							newrowfdebtord.put("AddMach", AddMach.trim());
							newrowfdebtord.put("RecordId", RecordId.trim());
							newrowfdebtord.put("timestamp_column",
									getCurrentTimeString().toString());
							newrowfdebtord.put("CrdPeriod", CrdPeriod.trim());
							newrowfdebtord.put("ChkCrdPrd", ChkCrdPrd.trim());
							newrowfdebtord.put("CrdLimit", CrdLimit.trim());
							newrowfdebtord.put("ChkCrdLmt", ChkCrdLmt.trim());
							newrowfdebtord.put("RepCode", RepCode.trim());
							newrowfdebtord.put("RankCode", RankCode.trim());
							newrowfdebtord.put("txndate",
									getCurrentTimeString().toString());
							newrowfdebtord.put("TranBatch", TranBatch.trim());
							String DebSumStr = DebCode.trim() + " : "
									+ DebName.trim();
							newrowfdebtord.put("DebSumary", DebSumStr);

							mydb.insert(ITEM_DEBTOR, null, newrowfdebtord);
							fdebtorduserrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 4: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerFdebtor.close();

			} catch (Exception e) {
				// Toast.makeText(this, evtoString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download fControl**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fControl/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfControl = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfControl.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfControl = jsonResponse
						.getJSONArray("fControlResult");
				Log.v(TAG,
						"Array Length Fdebtor :" + jsonArrayfControl.length());
				for (int i = 0; i < jsonArrayfControl.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfControl.get(i);
					String ComName = jObject.getString("ComName");
					String ComAdd1 = jObject.getString("ComAdd1");
					String ComAdd2 = jObject.getString("ComAdd2");
					String ComAdd3 = jObject.getString("ComAdd3");
					String comtel1 = jObject.getString("comtel1");
					String comtel2 = jObject.getString("comtel2");
					String comfax1 = jObject.getString("comfax1");
					String comemail = jObject.getString("comemail");
					String comweb = jObject.getString("comweb");
					// String confyear = jObject.getString("confyear");
					// String contyear = jObject.getString("contyear");
					String comRegNo = jObject.getString("comRegNo");
					// String ConfTxn = jObject.getString("ConfTxn");
					// String ContTxn = jObject.getString("ContTxn");
					String Crystalpath = jObject.getString("Crystalpath");
					String VatCmTaxNo = jObject.getString("VatCmTaxNo");
					String NbtCmTaxNo = jObject.getString("NbtCmTaxNo");
					String SysId = jObject.getString("SysId");
					String DealCode = jObject.getString("DealCode");
					String basecur = jObject.getString("basecur");
					String BalgCrLm = jObject.getString("BalgCrLm");
					String conage1 = jObject.getString("conage1");
					String conage2 = jObject.getString("conage2");
					String conage3 = jObject.getString("conage3");
					String conage4 = jObject.getString("conage4");
					String conage5 = jObject.getString("conage5");
					String conage6 = jObject.getString("conage6");
					String conage7 = jObject.getString("conage7");
					String conage8 = jObject.getString("conage8");
					String conage9 = jObject.getString("conage9");
					String conage10 = jObject.getString("conage10");
					String conage11 = jObject.getString("conage11");
					String conage12 = jObject.getString("conage12");
					String conage13 = jObject.getString("conage13");
					String conage14 = jObject.getString("conage14");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfcontrol = new ContentValues();
					Cursor fcontroluserrows = null;
					try {
						fcontroluserrows = mydb.query(ITEM_CONTROL, null,
								"SysId ='" + SysId.trim() + "'", null, null,
								null, null);
					} catch (Exception e) {
					}
					if (fcontroluserrows != null) {
						if (fcontroluserrows.getCount() >= 1) {
							Log.v(TAG, "Excisting fcontroluserrows 5");
						} else {
							Log.v(TAG, "fControl 5:" + SysId.trim());
							newrowfcontrol.put("ComName", ComName.trim());
							newrowfcontrol.put("ComAdd1", ComAdd1.trim());
							newrowfcontrol.put("ComAdd2", ComAdd2.trim());
							newrowfcontrol.put("ComAdd3", ComAdd3.trim());
							newrowfcontrol.put("comtel1", comtel1.trim());
							newrowfcontrol.put("comtel2", comtel2.trim());
							newrowfcontrol.put("comfax1", comfax1.trim());
							newrowfcontrol.put("comemail", comemail.trim());
							newrowfcontrol.put("comweb", comweb.trim());
							newrowfcontrol.put("confyear",
									getCurrentTimeString().toString());
							newrowfcontrol.put("contyear",
									getCurrentTimeString().toString());
							newrowfcontrol.put("comRegNo", comRegNo.trim());
							newrowfcontrol.put("ConfTxn",
									getCurrentTimeString().toString());
							newrowfcontrol.put("ContTxn",
									getCurrentTimeString().toString());
							newrowfcontrol.put("Crystalpath",
									Crystalpath.trim());
							newrowfcontrol.put("VatCmTaxNo", VatCmTaxNo.trim());
							newrowfcontrol.put("NbtCmTaxNo", NbtCmTaxNo.trim());
							newrowfcontrol.put("SysId", SysId.trim());
							newrowfcontrol.put("DealCode", DealCode.trim());
							newrowfcontrol.put("basecur", basecur.trim());
							newrowfcontrol.put("BalgCrLm", BalgCrLm.trim());
							newrowfcontrol.put("conage1", conage1.trim());
							newrowfcontrol.put("conage2", conage2.trim());
							newrowfcontrol.put("conage3", conage3.trim());
							newrowfcontrol.put("conage4", conage4.trim());
							newrowfcontrol.put("conage5", conage5.trim());
							newrowfcontrol.put("conage6", conage6.trim());
							newrowfcontrol.put("conage7", conage7.trim());
							newrowfcontrol.put("conage8", conage8.trim());
							newrowfcontrol.put("conage9", conage9.trim());
							newrowfcontrol.put("conage10", conage10.trim());
							newrowfcontrol.put("conage11", conage11.trim());
							newrowfcontrol.put("conage12", conage12.trim());
							newrowfcontrol.put("conage13", conage13.trim());
							newrowfcontrol.put("conage14", conage14.trim());
							mydb.insert(ITEM_CONTROL, null, newrowfcontrol);
							fcontroluserrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 5: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfControl.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// *****************Download fCompanySetting**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fCompanySetting/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfCompanySetting = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfCompanySetting.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfCompanySetting = jsonResponse
						.getJSONArray("fCompanySettingResult");
				Log.v(TAG, "Array Length fCompanySetting :"
						+ jsonArrayfCompanySetting.length());
				for (int i = 0; i < jsonArrayfCompanySetting.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfCompanySetting
							.get(i);

					String cSettingsCode = jObject.getString("cSettingsCode");
					String cSettingGrp = jObject.getString("cSettingGrp");
					String cLocationChar = jObject.getString("cLocationChar");
					String cCharVal = jObject.getString("cCharVal");
					String nNumVal = jObject.getString("nNumVal");
					String cRemarks = jObject.getString("cRemarks");
					String nType = jObject.getString("nType");
					String bUpdateFlag = jObject.getString("bUpdateFlag");
					String cCompanyCode = jObject.getString("cCompanyCode");
					String recordid = jObject.getString("recordid");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfCompanySetting = new ContentValues();
					Cursor fCompanySettingrows = null;
					try {
						fCompanySettingrows = mydb.query(ITEM_COMPANY_SETTING,
								null, "recordid ='" + recordid.trim() + "'",
								null, null, null, null);
					} catch (Exception e) {
					}
					if (fCompanySettingrows != null) {
						if (fCompanySettingrows.getCount() >= 1) {
							Log.v(TAG, "Excisting fCompanySettingrows 6");
						} else {
							Log.v(TAG, "fCompanySetting 6:" + recordid.trim());
							newrowfCompanySetting.put("cSettingsCode",
									cSettingsCode.trim());
							newrowfCompanySetting.put("cSettingGrp",
									cSettingGrp.trim());
							newrowfCompanySetting.put("cLocationChar",
									cLocationChar.trim());
							newrowfCompanySetting.put("cCharVal",
									cCharVal.trim());
							newrowfCompanySetting
									.put("nNumVal", nNumVal.trim());
							newrowfCompanySetting.put("cRemarks",
									cRemarks.trim());
							newrowfCompanySetting.put("nType ", nType.trim());
							newrowfCompanySetting.put("bUpdateFlag",
									bUpdateFlag.trim());
							newrowfCompanySetting.put("cCompanyCode",
									cCompanyCode.trim());
							newrowfCompanySetting.put("recordid",
									recordid.trim());
							newrowfCompanySetting.put("timestamp_column",
									getCurrentTimeString().toString());
							mydb.insert(ITEM_COMPANY_SETTING, null,
									newrowfCompanySetting);
							fCompanySettingrows.close();
						}
					}
					mydb.close();

				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 6: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfCompanySetting.close();
			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download fArea**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fArea/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfArea = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfArea.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfArea = jsonResponse
						.getJSONArray("fAreaResult");
				Log.v(TAG, "Array Length fArea :" + jsonArrayfArea.length());
				for (int i = 0; i < jsonArrayfArea.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfArea.get(i);

					// String fAreaID = jObject.getString("fAreaID");
					String AreaCode = jObject.getString("AreaCode");
					String AreaName = jObject.getString("AreaName");
					String RegCode = jObject.getString("RegCode");
					String DealCode = jObject.getString("DealCode");
					String AddUser = jObject.getString("AddUser");
					// String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String RecordId = jObject.getString("RecordId");
					// String timestamp_column =
					// jObject.getString("timestamp_column");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfArea = new ContentValues();
					Cursor fArearows = null;
					try {
						fArearows = mydb
								.query(ITEM_AREA, null, "RecordId ='"
										+ RecordId.trim() + "'", null, null,
										null, null);
					} catch (Exception e) {
					}
					if (fArearows != null) {
						if (fArearows.getCount() >= 1) {
							Log.v(TAG, "Excisting fArearows 7");
						} else {
							Log.v(TAG, "fArea 7:" + RecordId.trim());
							newrowfArea.put("AreaCode", AreaCode.trim());
							newrowfArea.put("AreaName", AreaName.trim());
							newrowfArea.put("RegCode", RegCode.trim());
							newrowfArea.put("DealCode", DealCode.trim());
							newrowfArea.put("AddUser", AddUser.trim());
							newrowfArea.put("AddDatefarea",
									getCurrentTimeString().toString());
							newrowfArea.put("AddMach", AddMach.trim());
							newrowfArea.put("RecordId", RecordId.trim());
							newrowfArea.put("timestamp_column",
									getCurrentTimeString().toString());
							mydb.insert(ITEM_AREA, null, newrowfArea);
							fArearows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 7: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfArea.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// *****************Download fLocations**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fLocations/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfLocations = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfLocations.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfLocations = jsonResponse
						.getJSONArray("fLocationsResult");
				Log.v(TAG,
						"Array Length fLocations :"
								+ jsonArrayfLocations.length());
				for (int i = 0; i < jsonArrayfLocations.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfLocations
							.get(i);
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String Address1 = jObject.getString("Address1");
					String Address2 = jObject.getString("Address2");
					String Address3 = jObject.getString("Address3");
					String Contact = jObject.getString("Contact");
					String EMail = jObject.getString("EMail");
					String FaxNo = jObject.getString("FaxNo");
					String LocCode = jObject.getString("LocCode");
					String LocName = jObject.getString("LocName");
					String LoctCode = jObject.getString("LoctCode");
					String RecordId = jObject.getString("RecordId");
					String RepCode = jObject.getString("RepCode");
					String TeleNo = jObject.getString("TeleNo");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowflocation = new ContentValues();
					Cursor newrowflocationrows = null;
					try {
						newrowflocationrows = mydb.query(ITEM_LOCATION, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (newrowflocationrows != null) {
						if (newrowflocationrows.getCount() >= 1) {
							Log.v(TAG, "Excisting newrowflocationrows 8");
						} else {
							Log.v(TAG, "fLocations 8:" + RecordId.trim());
							newrowflocation.put("AddMach", AddMach.trim());
							newrowflocation.put("AddUser", AddUser.trim());
							newrowflocation.put("Address1", Address1.trim());
							newrowflocation.put("Address2", Address2.trim());
							newrowflocation.put("Address3", Address3.trim());
							newrowflocation.put("Contact", Contact.trim());
							newrowflocation.put("EMail", EMail.trim());
							newrowflocation.put("FaxNo", FaxNo.trim());
							newrowflocation.put("LocCode", LocCode.trim());
							newrowflocation.put("LocName", LocName.trim());
							newrowflocation.put("LoctCode", LoctCode.trim());
							newrowflocation.put("RecordId", RecordId.trim());
							newrowflocation.put("RepCode", RepCode.trim());
							newrowflocation.put("TeleNo", TeleNo.trim());
							newrowflocation.put("LocAddDate",
									getCurrentTimeString().toString());
							mydb.insert(ITEM_LOCATION, null, newrowflocation);
							newrowflocationrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 8: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfLocations.close();
			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// *****************Download FCompanyBranch**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/FCompanyBranch/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfCompanyBranchResult = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfCompanyBranchResult.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayFCompanyBranch = jsonResponse
						.getJSONArray("FCompanyBranchResult");
				Log.v(TAG, "Array Length FCompanyBranch :"
						+ jsonArrayFCompanyBranch.length());
				for (int i = 0; i < jsonArrayFCompanyBranch.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayFCompanyBranch
							.get(i);

					String BranchCode = jObject.getString("BranchCode");
					String RecordId = jObject.getString("RecordId");
					String cSettingsCode = jObject.getString("cSettingsCode");
					String nNumVal = jObject.getString("nNumVal");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowreaderfRepbranchrows = new ContentValues();
					Cursor newrowflRebranchprows = null;
					try {
						newrowflRebranchprows = mydb.query(INV_COMPANY_BRANCH,
								null, "RecordId ='" + RecordId.trim() + "'",
								null, null, null, null);
					} catch (Exception e) {
					}
					if (newrowflRebranchprows != null) {
						if (newrowflRebranchprows.getCount() >= 1) {
							Log.v(TAG, "Excisting newrowflRebranchprows 9");
						} else {
							Log.v(TAG,
									"FCompanyBranch 9:" + cSettingsCode.trim());
							newrowreaderfRepbranchrows.put("BranchCode",
									BranchCode.trim());
							newrowreaderfRepbranchrows.put("RecordId",
									RecordId.trim());
							newrowreaderfRepbranchrows.put("cSettingsCode",
									cSettingsCode.trim());
							newrowreaderfRepbranchrows.put("nNumVal",
									nNumVal.trim());

							mydb.insert(INV_COMPANY_BRANCH, null,
									newrowreaderfRepbranchrows);
							newrowflRebranchprows.close();
						}

						mydb.close();
					}
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 9: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfCompanyBranchResult.close();
			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// *****************Download fSalRep**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fSalRep/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfSalRepResult = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfSalRepResult.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfSalRep = jsonResponse
						.getJSONArray("fSalRepResult");
				Log.v(TAG, "Array Length fSalRep :" + jsonArrayfSalRep.length());
				for (int i = 0; i < jsonArrayfSalRep.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfSalRep.get(i);
					String ASECode = jObject.getString("ASECode");
					String AreaCode = jObject.getString("AreaCode");
					String DealCode = jObject.getString("DealCode");
					String RecordId = jObject.getString("RecordId");
					String RepCode = jObject.getString("RepCode");
					String RepPrefix = jObject.getString("RepPrefix");
					String RepTCode = jObject.getString("RepTCode");
					String RepTele = jObject.getString("RepTele");
					String RepMob = jObject.getString("RepMob");
					String RepEMail = jObject.getString("RepEMail");
					String RepName = jObject.getString("RepName");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowreaderfSalReprows = new ContentValues();
					Cursor newrowfSalReprows = null;
					try {
						newrowfSalReprows = mydb.query(INV_SAL_REP, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (newrowfSalReprows != null) {
						if (newrowfSalReprows.getCount() >= 1) {
							Log.v(TAG, "Excisting newrowfSalReprows 10");
						} else {
							Log.v(TAG, "fSalRep 10:" + RepCode.trim());
							newrowreaderfSalReprows.put("ASECode",
									ASECode.trim());
							newrowreaderfSalReprows.put("AreaCode",
									AreaCode.trim());
							newrowreaderfSalReprows.put("DealCode",
									DealCode.trim());
							newrowreaderfSalReprows.put("RecordId",
									RecordId.trim());
							newrowreaderfSalReprows.put("RepCode",
									RepCode.trim());
							newrowreaderfSalReprows.put("RepPrefix",
									RepPrefix.trim());
							newrowreaderfSalReprows.put("RepTCode",
									RepTCode.trim());
							newrowreaderfSalReprows.put("repPhoneNo", RepTele);
							newrowreaderfSalReprows.put("RepMob", RepMob);
							newrowreaderfSalReprows.put("RepEMail", RepEMail);
							newrowreaderfSalReprows.put("RepName", RepName);

							mydb.insert(INV_SAL_REP, null,
									newrowreaderfSalReprows);
							newrowfSalReprows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 10: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfSalRepResult.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download FOrdHed**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/FOrdHed/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfstordhed = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfstordhed.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayFOrdHed = jsonResponse
						.getJSONArray("FOrdHedResult");
				Log.v(TAG, "Array Length FOrdHed :" + jsonArrayFOrdHed.length());
				for (int i = 0; i < jsonArrayFOrdHed.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayFOrdHed.get(i);

					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String AreaCode = jObject.getString("AreaCode");
					String CostCode = jObject.getString("CostCode");
					String CurCode = jObject.getString("CurCode");
					String CurRate = jObject.getString("CurRate");
					String DealCode = jObject.getString("DealCode");
					String DebCode = jObject.getString("DebCode");
					String InvAmt = jObject.getString("InvAmt");
					String InvDis = jObject.getString("InvDis");
					String InvFlg = jObject.getString("InvFlg");
					String LocCode = jObject.getString("LocCode");
					String ManuRef = jObject.getString("ManuRef");
					String OutDis = jObject.getString("OutDis");
					String RecordId = jObject.getString("RecordId");
					String RefNo = jObject.getString("RefNo");
					String Remarks = jObject.getString("Remarks");
					String RepCode = jObject.getString("RepCode");
					String RouteCode = jObject.getString("RouteCode");
					String TotMkrAmt = jObject.getString("TotMkrAmt");
					String TotalAmt = jObject.getString("TotalAmt");
					String TotalDis = jObject.getString("TotalDis");
					String TranBatch = jObject.getString("TranBatch");
					String TxnType = jObject.getString("TxnType");
					String UnOvAmt = jObject.getString("UnOvAmt");
					String prtcopy = jObject.getString("prtcopy");
					String TxnDate = jObject.getString("TxnDate");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfstordhed = new ContentValues();
					Cursor cursorfstordhed = null;
					try {
						cursorfstordhed = mydb.query(STOCK_ORDER_HEAD, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (cursorfstordhed != null) {
						if (cursorfstordhed.getCount() >= 1) {
							Log.v(TAG, "Excisting cursorfstordhed 11");
						} else {
							Log.v(TAG, "FOrdHed 11:" + RecordId.trim());
							newrowfstordhed.put("AddMach", AddMach.trim());
							newrowfstordhed.put("AddUser", AddUser.trim());
							newrowfstordhed.put("AreaCode", AreaCode.trim());
							newrowfstordhed.put("CostCode", CostCode.trim());
							newrowfstordhed.put("CurCode", CurCode.trim());
							newrowfstordhed.put("CurRate", CurRate.trim());
							newrowfstordhed.put("DealCode", DealCode.trim());
							newrowfstordhed.put("DebCode", DebCode.trim());
							newrowfstordhed.put("InvAmt", InvAmt.trim());
							newrowfstordhed.put("InvDis", InvDis.trim());
							newrowfstordhed.put("InvFlg", InvFlg.trim());
							newrowfstordhed.put("LocCode", LocCode.trim());
							newrowfstordhed.put("ManuRef", ManuRef.trim());
							newrowfstordhed.put("OutDis", OutDis.trim());
							newrowfstordhed.put("RecordId", RecordId.trim());
							newrowfstordhed.put("RefNo", RefNo.trim());
							newrowfstordhed.put("Remarks", Remarks.trim());
							newrowfstordhed.put("RepCode", RepCode.trim());
							newrowfstordhed.put("RouteCode", RouteCode.trim());
							newrowfstordhed.put("TotMkrAmt", TotMkrAmt.trim());
							newrowfstordhed.put("TotalAmt", TotalAmt.trim());
							newrowfstordhed.put("TotalDis", TotalDis.trim());
							newrowfstordhed.put("TranBatch", TranBatch.trim());
							newrowfstordhed.put("TxnType", TxnType.trim());
							newrowfstordhed.put("UnOvAmt", UnOvAmt.trim());
							newrowfstordhed.put("prtcopy", prtcopy.trim());
							newrowfstordhed.put("TxnDate", TxnDate.trim());
							newrowfstordhed.put("stOrderComplete", "0");
							newrowfstordhed.put("ohAddDate", TxnDate.trim());
							mydb.insert(STOCK_ORDER_HEAD, null, newrowfstordhed);
							cursorfstordhed.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 11: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfstordhed.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// *****************Download FOrddet**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/FOrddet/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfstorddet = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfstorddet.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayFOrddet = jsonResponse
						.getJSONArray("FOrddetResult");
				Log.v(TAG, "Array Length FOrddet :" + jsonArrayFOrddet.length());
				for (int i = 0; i < jsonArrayFOrddet.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayFOrddet.get(i);

					String Amt = jObject.getString("Amt");
					String BAmt = jObject.getString("BAmt");
					String BDisAmt = jObject.getString("BDisAmt");
					String BSellPrice = jObject.getString("BSellPrice");
					String BTSellPrice = jObject.getString("BTSellPrice");
					String BTaxAmt = jObject.getString("BTaxAmt");
					String BalQty = jObject.getString("BalQty");
					String CaseQty = jObject.getString("CaseQty");
					String CostPrice = jObject.getString("CostPrice");
					String DisAmt = jObject.getString("DisAmt");
					String DisPer = jObject.getString("DisPer");
					String Itemcode = jObject.getString("Itemcode");
					String PiceQty = jObject.getString("PiceQty");
					String Qty = jObject.getString("Qty");
					String ReaCode = jObject.getString("ReaCode");
					String RecordId = jObject.getString("RecordId");
					String RefNo = jObject.getString("RefNo");
					String SellPrice = jObject.getString("SellPrice");
					String SeqNo = jObject.getString("SeqNo");
					String TSellPrice = jObject.getString("TSellPrice");
					String TaxAmt = jObject.getString("TaxAmt");
					String TxnType = jObject.getString("TxnType");
					String Txnseqno = jObject.getString("Txnseqno");
					String Type = jObject.getString("Type");
					String TxnDate = jObject.getString("TxnDate");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfstorddet = new ContentValues();
					Cursor cursorfstorddet = null;
					try {
						cursorfstorddet = mydb.query(STOCK_ORDER_DETAIL, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (cursorfstorddet != null) {
						if (cursorfstorddet.getCount() >= 1) {
							Log.v(TAG, "Excisting cursorfstorddet 12");
						} else {
							Log.v(TAG, "FOrddet 12:" + RecordId.trim());
							newrowfstorddet.put("Amt", Amt.trim());
							newrowfstorddet.put("BAmt", BAmt.trim());
							newrowfstorddet.put("BDisAmt", BDisAmt.trim());
							newrowfstorddet
									.put("BSellPrice", BSellPrice.trim());
							newrowfstorddet.put("BTSellPrice",
									BTSellPrice.trim());
							newrowfstorddet.put("BTaxAmt", BTaxAmt.trim());
							newrowfstorddet.put("BalQty", BalQty.trim());
							newrowfstorddet.put("CaseQty", CaseQty.trim());
							newrowfstorddet.put("CostPrice", CostPrice.trim());
							newrowfstorddet.put("DisAmt", DisAmt.trim());
							newrowfstorddet.put("DisPer", DisPer.trim());
							newrowfstorddet.put("Itemcode", Itemcode.trim());
							newrowfstorddet.put("PiceQty", PiceQty.trim());
							newrowfstorddet.put("Qty", Qty.trim());
							newrowfstorddet.put("ReaCode", ReaCode.trim());
							newrowfstorddet.put("RecordId", RecordId.trim());
							newrowfstorddet.put("RefNo", RefNo.trim());
							newrowfstorddet.put("SellPrice", SellPrice.trim());
							newrowfstorddet.put("SeqNo", SeqNo.trim());
							newrowfstorddet
									.put("TSellPrice", TSellPrice.trim());
							newrowfstorddet.put("TaxAmt", TaxAmt.trim());
							newrowfstorddet.put("TxnType", TxnType.trim());
							newrowfstorddet.put("Txnseqno", Txnseqno.trim());
							newrowfstorddet.put("Type", Type.trim());
							newrowfstorddet.put("TxnDate", TxnDate.trim());
							newrowfstorddet.put("storddetSync", "0");
							mydb.insert(STOCK_ORDER_DETAIL, null,
									newrowfstorddet);
							cursorfstorddet.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 12: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfstorddet.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download fReason**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fReason/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfReason = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfReason.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfReason = jsonResponse
						.getJSONArray("fReasonResult");
				Log.v(TAG, "Array Length fReason :" + jsonArrayfReason.length());
				for (int i = 0; i < jsonArrayfReason.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfReason.get(i);

					String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String ReaCode = jObject.getString("ReaCode");
					String ReaName = jObject.getString("ReaName");
					String ReaTcode = jObject.getString("ReaTcode");
					String RecordId = jObject.getString("RecordId");
					String Type = jObject.getString("Type");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfReason = new ContentValues();
					Cursor fReasonSettingrows = null;
					try {
						fReasonSettingrows = mydb.query(SALES_ORD_REASON, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (fReasonSettingrows != null) {
						if (fReasonSettingrows.getCount() >= 1) {
							Log.v(TAG, "Excisting fReasonSettingrows 13");
						} else {
							Log.v(TAG, "fReason 13:" + ReaCode.trim());
							newrowfReason.put("AddDate", AddDate.trim());
							newrowfReason.put("AddMach", AddMach.trim());
							newrowfReason.put("AddUser", AddUser.trim());
							newrowfReason.put("ReaCode", ReaCode.trim());
							newrowfReason.put("ReaName", ReaName.trim());
							newrowfReason.put("ReaTcode", ReaTcode.trim());
							newrowfReason.put("RecordId ", RecordId.trim());
							newrowfReason.put("Type", Type.trim());
							mydb.insert(SALES_ORD_REASON, null, newrowfReason);
							fReasonSettingrows.close();
						}
					}
					mydb.close();

				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 13: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfReason.close();
			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download fRoute**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fRoute/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfRoute = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfRoute.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfRoute = jsonResponse
						.getJSONArray("fRouteResult");
				Log.v(TAG, "Array Length fRoute :" + jsonArrayfRoute.length());
				for (int i = 0; i < jsonArrayfRoute.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfRoute.get(i);
					String RepCode = jObject.getString("RepCode");
					String RouteCode = jObject.getString("RouteCode");
					String RouteName = jObject.getString("RouteName");
					String RecordId = jObject.getString("RecordId");
					String AddDate = jObject.getString("AddDate");
					String AreaCode = jObject.getString("AreaCode");
					String DealCode = jObject.getString("DealCode");
					String FreqNo = jObject.getString("FreqNo");
					String Km = jObject.getString("Km");
					String MinProcall = jObject.getString("MinProcall");
					String RDAloRate = jObject.getString("RDAloRate");
					String RDTarget = jObject.getString("RDTarget");
					String Remarks = jObject.getString("Remarks");
					String Status = jObject.getString("Status");
					String Tonnage = jObject.getString("Tonnage");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfRoute = new ContentValues();
					Cursor frouterows = null;
					try {
						frouterows = mydb.query(SALES_REP_ROUTE, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (frouterows != null) {
						if (frouterows.getCount() >= 1) {
							Log.v(TAG, "Excisting frouterows 14");
						} else {
							Log.v(TAG, "fRoute 14:" + RouteCode.trim());
							newrowfRoute.put("RepCode", RepCode.trim());
							newrowfRoute.put("RouteCode", RouteCode.trim());
							newrowfRoute.put("RouteName", RouteName.trim());
							newrowfRoute.put("RecordId", RecordId.trim());
							newrowfRoute.put("AddDate", AddDate.trim());
							newrowfRoute.put("AreaCode", AreaCode.trim());
							newrowfRoute.put("DealCode", DealCode.trim());
							newrowfRoute.put("FreqNo", FreqNo.trim());
							newrowfRoute.put("Km", Km.trim());
							newrowfRoute.put("MinProcall", MinProcall.trim());
							newrowfRoute.put("RDAloRate", RDAloRate.trim());
							newrowfRoute.put("RDTarget", RDTarget.trim());
							newrowfRoute.put("Remarks", Remarks.trim());
							newrowfRoute.put("Status", Status.trim());
							newrowfRoute.put("Tonnage", Tonnage.trim());
							mydb.insert(SALES_REP_ROUTE, null, newrowfRoute);
							frouterows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 14: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfRoute.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// *****************Download fbank**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fbank/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfbank = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfbank.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfbank = jsonResponse
						.getJSONArray("fbankResult");
				Log.v(TAG, "Array Length fbank :" + jsonArrayfbank.length());
				for (int i = 0; i < jsonArrayfbank.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfbank.get(i);
					String RecordId = jObject.getString("RecordId");
					String bankcode = jObject.getString("bankcode");
					String bankname = jObject.getString("bankname");
					String bankaccno = jObject.getString("bankaccno");
					String Branch = jObject.getString("Branch");
					String bankadd1 = jObject.getString("bankadd1");
					String bankadd2 = jObject.getString("bankadd2");
					String AddDate = jObject.getString("AddDate");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfbank = new ContentValues();
					Cursor adminuserrows = null;
					try {
						adminuserrows = mydb.query(BANK_DETAILS, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (adminuserrows != null) {
						if (adminuserrows.getCount() >= 1) {
							Log.v(TAG, "Excisting adminuserrows 15");
						} else {
							Log.v(TAG, "fbank 15:" + bankcode.trim());
							newrowfbank.put("RecordId", RecordId.trim());
							newrowfbank.put("bankcode", bankcode.trim());
							newrowfbank.put("bankname", bankname.trim());
							newrowfbank.put("bankaccno", bankaccno.trim());
							newrowfbank.put("Branch", Branch.trim());
							newrowfbank.put("bankadd1", bankadd1.trim());
							newrowfbank.put("bankadd2", bankadd2.trim());
							newrowfbank.put("AddDate", AddDate.trim());
							mydb.insert(BANK_DETAILS, null, newrowfbank);
							adminuserrows.close();
						}

					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 15: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfbank.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// ***************Download fDdbNote*********************************
			// TODO Auto-generated method stub
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fDdbNote/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfDdbNote = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfDdbNote.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfDdbNote = jsonResponse
						.getJSONArray("fDdbNoteResult");
				Log.v(TAG,
						"Array Length fDdbNote :" + jsonArrayfDdbNote.length());
				for (int i = 0; i < jsonArrayfDdbNote.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfDdbNote.get(i);
					String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String Amt = jObject.getString("Amt");
					String BAmt = jObject.getString("BAmt");
					String BTaxAmt = jObject.getString("BTaxAmt");
					String CrAcc = jObject.getString("CrAcc");
					String CurCode = jObject.getString("CurCode");
					String CurRate = jObject.getString("CurRate");
					String DebCode = jObject.getString("DebCode");
					String GlPost = jObject.getString("GlPost");
					String ManuRef = jObject.getString("ManuRef");
					String OvPayAmt = jObject.getString("OvPayAmt");
					String PrtCopy = jObject.getString("PrtCopy");
					String RecordId = jObject.getString("RecordId");
					String RefInv = jObject.getString("RefInv");
					String RefNo = jObject.getString("RefNo");
					String RefNo1 = jObject.getString("RefNo1");
					String Remarks = jObject.getString("Remarks");
					String RepCode = jObject.getString("RepCode");
					String SaleRefNo = jObject.getString("SaleRefNo");
					String TaxAmt = jObject.getString("TaxAmt");
					String TaxComCode = jObject.getString("TaxComCode");
					String TotBal = jObject.getString("TotBal");
					String TotBal1 = jObject.getString("TotBal1");
					String TxnDate = jObject.getString("TxnDate");
					try {
						date = originalFormat.parse(TxnDate.replaceAll(
								"[-+/.^:,]", " "));
						TxnDate = targetFormat.format(date);
					} catch (ParseException ex) {
						TxnDate = "1900-01-01";
					}
					String TxnType = jObject.getString("TxnType");
					String glbatch = jObject.getString("glbatch");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfDdbNote = new ContentValues();
					Cursor adminuserrows = null;
					try {
						adminuserrows = mydb.query(RECEIPT_INVOICES, null,
								"RefNo ='" + RefNo.trim() + "'", null, null,
								null, null);
					} catch (Exception e) {
					}
					if (adminuserrows != null) {
						if (adminuserrows.getCount() >= 1) {
							Log.v(TAG, "Excisting adminuserrows 16");
						} else {
							Log.v(TAG, "fDdbNote 16:" + RecordId.trim());
							newrowfDdbNote.put("RecordId", RecordId.trim());
							newrowfDdbNote.put("RefNo", RefNo.trim());
							newrowfDdbNote.put("RefInv", RefInv.trim());
							newrowfDdbNote.put("SaleRefNo", SaleRefNo.trim());
							newrowfDdbNote.put("ManuRef", ManuRef.trim());
							newrowfDdbNote.put("TxnType", TxnType.trim());
							newrowfDdbNote.put("TxnDate", TxnDate.trim());
							newrowfDdbNote.put("CurCode", CurCode.trim());
							newrowfDdbNote.put("CurRate", CurRate.trim());
							newrowfDdbNote.put("DebCode", DebCode.trim());
							newrowfDdbNote.put("RepCode", RepCode.trim());
							newrowfDdbNote.put("TaxComCode", TaxComCode.trim());
							newrowfDdbNote.put("TaxAmt", TaxAmt.trim());
							newrowfDdbNote.put("BTaxAmt", BTaxAmt.trim());
							newrowfDdbNote.put("Amt", Amt.trim());
							newrowfDdbNote.put("BAmt", BAmt.trim());
							newrowfDdbNote.put("TotBal", TotBal.trim());
							newrowfDdbNote.put("TotBal1", TotBal1.trim());
							newrowfDdbNote.put("OvPayAmt", OvPayAmt.trim());
							newrowfDdbNote.put("Remarks", Remarks.trim());
							newrowfDdbNote.put("CrAcc", CrAcc.trim());
							newrowfDdbNote.put("PrtCopy", PrtCopy.trim());
							newrowfDdbNote.put("GlPost", GlPost.trim());
							newrowfDdbNote.put("glbatch", glbatch.trim());
							newrowfDdbNote.put("AddUser", AddUser.trim());
							newrowfDdbNote.put("AddDate", AddDate.trim());
							newrowfDdbNote.put("AddMach", AddMach.trim());
							newrowfDdbNote.put("RefNo1", RefNo1.trim());
							mydb.insert(RECEIPT_INVOICES, null, newrowfDdbNote);
							adminuserrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 16: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfDdbNote.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download fExpense**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fExpense/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfexpense = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfexpense.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfExpense = jsonResponse
						.getJSONArray("fExpenseResult");
				Log.v(TAG,
						"Array Length fDdbNote :" + jsonArrayfExpense.length());
				for (int i = 0; i < jsonArrayfExpense.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArrayfExpense.get(i);
					String ExpCode = jObject.getString("ExpCode");
					String ExpGrpCode = jObject.getString("ExpGrpCode");
					String ExpName = jObject.getString("ExpName");
					String RecordId = jObject.getString("RecordId");
					String Status = jObject.getString("Status");
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfexpense = new ContentValues();
					Cursor adminuserrows = null;
					try {
						adminuserrows = mydb.query(USER_EXPENSE, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (adminuserrows != null) {
						if (adminuserrows.getCount() >= 1) {
							Log.v(TAG, "Excisting adminuserrows 17");
						} else {
							Log.v(TAG, "fExpense 17:" + ExpCode.trim());
							newrowfexpense.put("ExpCode", ExpCode.trim());
							newrowfexpense.put("ExpGrpCode", ExpGrpCode.trim());
							newrowfexpense.put("ExpName", ExpName.trim());
							newrowfexpense.put("RecordId", RecordId.trim());
							newrowfexpense.put("Status", Status.trim());
							newrowfexpense.put("AddMach", AddMach.trim());
							newrowfexpense.put("AddUser", AddUser.trim());
							mydb.insert(USER_EXPENSE, null, newrowfexpense);
							adminuserrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 17: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfexpense.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// *****************Download fTown**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fTown/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfTown = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfTown.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfTown = jsonResponse
						.getJSONArray("fTownResult");
				Log.v(TAG, "Array Length fTown :" + jsonArrayfTown.length());
				for (int i = 0; i < jsonArrayfTown.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArrayfTown.get(i);
					String RecordId = jObject.getString("RecordId");
					String TownCode = jObject.getString("TownCode");
					String TownName = jObject.getString("TownName");
					String DistrCode = jObject.getString("DistrCode");
					String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfTown = new ContentValues();
					Cursor adminuserrows = null;
					try {
						adminuserrows = mydb.query(TOWN_DETAILS, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (adminuserrows != null) {
						if (adminuserrows.getCount() >= 1) {
							Log.v(TAG, "Excisting adminuserrows 18");
						} else {
							Log.v(TAG, "fTown 18:" + TownCode.trim());
							newrowfTown.put("RecordId", RecordId.trim());
							newrowfTown.put("TownCode", TownCode.trim());
							newrowfTown.put("TownName", TownName.trim());
							newrowfTown.put("DistrCode", DistrCode.trim());
							newrowfTown.put("AddDate", AddDate.trim());
							newrowfTown.put("AddMach", AddMach.trim());
							newrowfTown.put("AddUser", AddUser.trim());
							mydb.insert(TOWN_DETAILS, null, newrowfTown);
							adminuserrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 4;
				Log.v(TAG, "arrayLength 18: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfTown.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// *****************Download FMerch**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/FMerch/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerFMerch = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerFMerch.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayFMerch = jsonResponse
						.getJSONArray("FMerchResult");
				Log.v(TAG, "Array Length FMerch :" + jsonArrayFMerch.length());
				for (int i = 0; i < jsonArrayFMerch.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArrayFMerch.get(i);
					String RecordId = jObject.getString("RecordId");
					String MerchCode = jObject.getString("MerchCode");
					String MerchName = jObject.getString("MerchName");
					String AddUser = jObject.getString("AddUser");
					String AddMach = jObject.getString("AddMach");
					String AddDate = jObject.getString("AddDate");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowFMerch = new ContentValues();
					Cursor adminuserrows = null;
					try {
						adminuserrows = mydb.query(MERCH_DETAILS, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (adminuserrows != null) {
						if (adminuserrows.getCount() >= 1) {
							Log.v(TAG, "Excisting adminuserrows 19");
						} else {
							Log.v(TAG, "FMerch 19:" + MerchCode.trim());
							newrowFMerch.put("RecordId", RecordId.trim());
							newrowFMerch.put("MerchCode", MerchCode.trim());
							newrowFMerch.put("MerchName", MerchName.trim());
							newrowFMerch.put("AddUser", AddUser.trim());
							newrowFMerch.put("AddMach", AddMach.trim());
							newrowFMerch.put("AddDate", AddDate.trim());

							mydb.insert(MERCH_DETAILS, null, newrowFMerch);
							adminuserrows.close();
						}

					}
					mydb.close();
				}
				arrayLength = 3;
				Log.v(TAG, "arrayLength 19: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerFMerch.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// ******Download Available fRouteDet details**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fRouteDet/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfdblist = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfdblist.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfRouteDet = jsonResponse
						.getJSONArray("fRouteDetResult");
				Log.v(TAG,
						"Array Length fRouteDet :"
								+ jsonArrayfRouteDet.length());
				for (int i = 0; i < jsonArrayfRouteDet.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfRouteDet.get(i);
					String RecordId = jObject.getString("RecordId");
					String DebCode = jObject.getString("DebCode");
					String RouteCode = jObject.getString("RouteCode");
					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowrepdetlist = new ContentValues();
					Cursor routedetlistrows = null;
					try {
						routedetlistrows = mydb.query(SALES_REP_ROUTEDET, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (routedetlistrows != null) {
						if (routedetlistrows.getCount() >= 1) {
							Log.v(TAG, "Excisting routedetlistrows 20");
						} else {
							Log.v(TAG, "fRouteDet 20:" + RecordId.trim());
							newrowrepdetlist.put("RecordId", RecordId.trim());
							newrowrepdetlist.put("DebCode", DebCode.trim());
							newrowrepdetlist.put("RouteCode", RouteCode.trim());
							mydb.insert(SALES_REP_ROUTEDET, null,
									newrowrepdetlist);
							routedetlistrows.close();
						}

					}
					mydb.close();
				}
				arrayLength = 3;
				Log.v(TAG, "arrayLength 20: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfdblist.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// ******Download Available FTrgCapUL details**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/FTrgCapUL/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerFTrgCapUL = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerFTrgCapUL.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayFTrgCapUL = jsonResponse
						.getJSONArray("FTrgCapULResult");
				Log.v(TAG,
						"Array Length FTrgCapUL :"
								+ jsonArrayFTrgCapUL.length());
				for (int i = 0; i < jsonArrayFTrgCapUL.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArrayFTrgCapUL.get(i);
					String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String DealCode = jObject.getString("DealCode");
					String Month = jObject.getString("Month");
					String Qty = jObject.getString("Qty");
					String RecordId = jObject.getString("RecordId");
					String RepCode = jObject.getString("RepCode");
					String SKUCode = jObject.getString("SKUCode");
					String Year = jObject.getString("Year");
					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowftrgcapul = new ContentValues();
					Cursor ftrgcapulrows = null;
					try {
						ftrgcapulrows = mydb.query(FTRGCAPUL, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (ftrgcapulrows != null) {
						if (ftrgcapulrows.getCount() >= 1) {
							Log.v(TAG, "Excisting ftrgcapulrows 21");
						} else
							Log.v(TAG, "FTrgCapUL 21:" + RecordId.trim());
						newrowftrgcapul.put("AddDate", AddDate.trim());
						newrowftrgcapul.put("AddMach", AddMach.trim());
						newrowftrgcapul.put("AddMach", AddMach.trim());
						newrowftrgcapul.put("AddUser", AddUser.trim());
						newrowftrgcapul.put("DealCode", DealCode.trim());
						newrowftrgcapul.put("Month", Month.trim());
						newrowftrgcapul.put("Qty", Qty.trim());
						newrowftrgcapul.put("RecordId", RecordId.trim());
						newrowftrgcapul.put("RepCode", RepCode.trim());
						newrowftrgcapul.put("SKUCode", SKUCode.trim());
						newrowftrgcapul.put("Year", Year.trim());
						mydb.insert(FTRGCAPUL, null, newrowftrgcapul);
						ftrgcapulrows.close();

					}
					mydb.close();
				}
				arrayLength = 3;
				Log.v(TAG, "arrayLength 21: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerFTrgCapUL.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// ******Download Available fType details**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fType/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfType = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfType.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfType = jsonResponse
						.getJSONArray("fTypeResult");
				Log.v(TAG, "Array Length fType :" + jsonArrayfType.length());
				for (int i = 0; i < jsonArrayfType.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArrayfType.get(i);
					String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String RecordId = jObject.getString("RecordId");
					String TypeCode = jObject.getString("TypeCode");
					String TypeName = jObject.getString("TypeName");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowftype = new ContentValues();
					Cursor ftyperows = null;
					try {
						ftyperows = mydb
								.query(FTYPE, null,
										"RecordId ='" + RecordId.trim() + "'",
										null, null, null, null);
					} catch (Exception e) {
					}
					if (ftyperows != null) {
						if (ftyperows.getCount() >= 1) {
							Log.v(TAG, "Excisting ftyperows 22");
						} else {
							Log.v(TAG, "fType 22:" + RecordId.trim());
							newrowftype.put("AddDate", AddDate.trim());
							newrowftype.put("AddMach", AddMach.trim());
							newrowftype.put("AddUser", AddUser.trim());
							newrowftype.put("RecordId", RecordId.trim());
							newrowftype.put("TypeCode", TypeCode.trim());
							newrowftype.put("TypeName", TypeName.trim());
							mydb.insert(FTYPE, null, newrowftype);
							ftyperows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 3;
				Log.v(TAG, "arrayLength 22: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfType.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// ******Download Available fSubBrand details**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fSubBrand/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfSubBrand = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfSubBrand.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfSubBrand = jsonResponse
						.getJSONArray("fSubBrandResult");
				Log.v(TAG,
						"Array Length fSubBrand :"
								+ jsonArrayfSubBrand.length());
				for (int i = 0; i < jsonArrayfSubBrand.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArrayfSubBrand.get(i);
					String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String RecordId = jObject.getString("RecordId");
					String SBrandCode = jObject.getString("SBrandCode");
					String SBrandName = jObject.getString("SBrandName");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfSubBrand = new ContentValues();
					Cursor fSubBrandrows = null;
					try {
						fSubBrandrows = mydb.query(FSUBBRAND, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (fSubBrandrows != null) {
						if (fSubBrandrows.getCount() >= 1) {
							Log.v(TAG, "Excisting fSubBrandrows 23");
						} else
							Log.v(TAG, "fSubBrand: 23" + RecordId.trim());
						newrowfSubBrand.put("AddDate", AddDate.trim());
						newrowfSubBrand.put("AddMach", AddMach.trim());
						newrowfSubBrand.put("AddUser", AddUser.trim());
						newrowfSubBrand.put("RecordId", RecordId.trim());
						newrowfSubBrand.put("SBrandCode", SBrandCode.trim());
						newrowfSubBrand.put("SBrandName", SBrandName.trim());
						mydb.insert(FSUBBRAND, null, newrowfSubBrand);
						fSubBrandrows.close();
					}
					mydb.close();
				}
				arrayLength = 3;
				Log.v(TAG, "arrayLength 23: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfSubBrand.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// ******Download Available fGroup details**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fGroup/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfGroup = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfGroup.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfGroup = jsonResponse
						.getJSONArray("fGroupResult");
				Log.v(TAG, "Array Length fGroup :" + jsonArrayfGroup.length());
				for (int i = 0; i < jsonArrayfGroup.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArrayfGroup.get(i);
					String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String GroupCode = jObject.getString("GroupCode");
					String GroupName = jObject.getString("GroupName");
					String RecordId = jObject.getString("RecordId");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfGroup = new ContentValues();
					Cursor fGrouprows = null;
					try {
						fGrouprows = mydb
								.query(FGROUP, null,
										"RecordId ='" + RecordId.trim() + "'",
										null, null, null, null);
					} catch (Exception e) {
					}
					if (fGrouprows != null) {
						if (fGrouprows.getCount() >= 1) {
							Log.v(TAG, "Excisting fGrouprows 24");
						} else {
							Log.v(TAG, "fGroup 24:" + RecordId.trim());
							newrowfGroup.put("AddDate", AddDate.trim());
							newrowfGroup.put("AddMach", AddMach.trim());
							newrowfGroup.put("AddUser", AddUser.trim());
							newrowfGroup.put("GroupCode", GroupCode.trim());
							newrowfGroup.put("GroupName", GroupName.trim());
							newrowfGroup.put("RecordId", RecordId.trim());
							mydb.insert(FGROUP, null, newrowfGroup);
							fGrouprows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 3;
				Log.v(TAG, "arrayLength 24: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfGroup.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// ******Download Available FSKU details**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/FSKU/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfsku = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfsku.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayFSKU = jsonResponse
						.getJSONArray("FSKUResult");
				Log.v(TAG, "Array Length FSKU :" + jsonArrayFSKU.length());
				for (int i = 0; i < jsonArrayFSKU.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArrayFSKU.get(i);
					String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String BrandCode = jObject.getString("BrandCode");
					String GroupCode = jObject.getString("GroupCode");
					String ItemStatus = jObject.getString("ItemStatus");
					String MustSale = jObject.getString("MustSale");
					String NOUCase = jObject.getString("NOUCase");
					String OrdSeq = jObject.getString("OrdSeq");
					String RecordId = jObject.getString("RecordId");
					String SBrandCode = jObject.getString("SBrandCode");
					String SKUCode = jObject.getString("SKUCode");
					String SkuName = jObject.getString("SkuName");
					String SkuSizCode = jObject.getString("SkuSizCode");
					String Tonnage = jObject.getString("Tonnage");
					String TypeCode = jObject.getString("TypeCode");
					String Unit = jObject.getString("Unit");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfsku = new ContentValues();
					Cursor fskurows = null;
					try {
						fskurows = mydb
								.query(FSKU, null,
										"RecordId ='" + RecordId.trim() + "'",
										null, null, null, null);
					} catch (Exception e) {
					}
					if (fskurows != null) {
						if (fskurows.getCount() >= 1) {
							Log.v(TAG, "Excisting fskurows 25");
						} else {
							Log.v(TAG, "FSKU 25:" + RecordId.trim());
							newrowfsku.put("AddDate", AddDate.trim());
							newrowfsku.put("AddMach", AddMach.trim());
							newrowfsku.put("AddUser", AddUser.trim());
							newrowfsku.put("BrandCode", BrandCode.trim());
							newrowfsku.put("GroupCode", GroupCode.trim());
							newrowfsku.put("ItemStatus", ItemStatus.trim());
							newrowfsku.put("MustSale", MustSale.trim());
							newrowfsku.put("NOUCase", NOUCase.trim());
							newrowfsku.put("OrdSeq", OrdSeq.trim());
							newrowfsku.put("RecordId", RecordId.trim());
							newrowfsku.put("SBrandCode", SBrandCode.trim());
							newrowfsku.put("SKUCode", SKUCode.trim());
							newrowfsku.put("SkuName", SkuName.trim());
							newrowfsku.put("SkuSizCode", SkuSizCode.trim());
							newrowfsku.put("Tonnage", Tonnage.trim());
							newrowfsku.put("TypeCode", TypeCode.trim());
							newrowfsku.put("Unit", Unit.trim());
							mydb.insert(FSKU, null, newrowfsku);
							fskurows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 3;
				Log.v(TAG, "arrayLength 25: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfsku.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			// ******Download Available fbrand details**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fbrand/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfbrand = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfbrand.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayFbrand = jsonResponse
						.getJSONArray("FbrandResult");
				Log.v(TAG, "Array Length Fbrand :" + jsonArrayFbrand.length());
				for (int i = 0; i < jsonArrayFbrand.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArrayFbrand.get(i);
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String BrandCode = jObject.getString("BrandCode");
					String BrandName = jObject.getString("BrandName");
					String RecordId = jObject.getString("RecordId");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfbrand = new ContentValues();
					Cursor fbrandrows = null;
					try {
						fbrandrows = mydb
								.query(FBRAND, null,
										"RecordId ='" + RecordId.trim() + "'",
										null, null, null, null);
					} catch (Exception e) {
					}
					if (fbrandrows != null) {
						if (fbrandrows.getCount() >= 1) {
							Log.v(TAG, "Excisting fbrandrows 26");
						} else {
							Log.v(TAG, "fbrand 26:" + RecordId.trim());
							newrowfbrand.put("AddMach", AddMach.trim());
							newrowfbrand.put("AddUser", AddUser.trim());
							newrowfbrand.put("BrandCode", BrandCode.trim());
							newrowfbrand.put("BrandName", BrandName.trim());
							newrowfbrand.put("RecordId", RecordId.trim());
							mydb.insert(FBRAND, null, newrowfbrand);
							fbrandrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 3;
				Log.v(TAG, "arrayLength 26: " + arrayLength);
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfbrand.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// ******Download Available fDealer details**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fDealer/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfDealer = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfDealer.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArray = jsonResponse
						.getJSONArray("fDealerResult");

				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject jObject = (JSONObject) jsonArray.get(i);

					String DealCode = jObject.getString("DealCode");
					String DealName = jObject.getString("DealName");
					String DealAdd1 = jObject.getString("DealAdd1");
					String DealAdd2 = jObject.getString("DealAdd2");
					String DealAdd3 = jObject.getString("DealAdd3");
					String DealTele = jObject.getString("DealTele");
					String DealMob = jObject.getString("DealMob");
					String DealEMail = jObject.getString("DealEMail");
					String Status = jObject.getString("Status");
					String Distance = jObject.getString("Distance");
					String DealGdCode = jObject.getString("DealGdCode");
					String CusTypCode = jObject.getString("CusTypCode");
					String AddUser = jObject.getString("AddUser");
					String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String RecordId = jObject.getString("RecordId");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfDealer = new ContentValues();
					Cursor fdealerrows = null;
					try {
						fdealerrows = mydb.query(SALES_DEALER, null,
								"RecordId ='" + RecordId.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (fdealerrows != null) {
						if (fdealerrows.getCount() >= 1) {
							Log.v(TAG, "Excisting fdealerrows 25");
						} else {
							Log.v(TAG, "fDealer 25:" + RecordId.trim());
							newrowfDealer.put("DealCode", DealCode.trim());
							newrowfDealer.put("DealName", DealName.trim());
							newrowfDealer.put("DealAdd1", DealAdd1.trim());
							newrowfDealer.put("DealAdd2", DealAdd2.trim());
							newrowfDealer.put("DealAdd3", DealAdd3.trim());
							newrowfDealer.put("DealTele", DealTele.trim());
							newrowfDealer.put("DealMob", DealMob.trim());
							newrowfDealer.put("DealEMail", DealEMail.trim());
							newrowfDealer.put("Status", Status.trim());
							newrowfDealer.put("Distance", Distance.trim());
							newrowfDealer.put("DealGdCode", DealGdCode.trim());
							newrowfDealer.put("CusTypCode", CusTypCode.trim());
							newrowfDealer.put("AddUser", AddUser.trim());
							newrowfDealer.put("AddDate", AddDate.trim());
							newrowfDealer.put("AddMach", AddMach.trim());
							newrowfDealer.put("RecordId", RecordId.trim());
							mydb.insert(SALES_DEALER, null, newrowfDealer);
							fdealerrows.close();
						}
					}
					mydb.close();
				}
				arrayLength = 3;
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfDealer.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			mydb.close();
			arrayLength = 3;
			progressHandler.sendMessage(progressHandler.obtainMessage());
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {

			if (NetFail == 0) {
				mProgressDialog.dismiss();
				try {
					showDialog(DIALOG_SYNC_SUCCESS);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			} else if (NetFail == 404) {
				countDownActivator();
				/*
				 * showAlertDialog(DM_InvoiceMenu.this,
				 * "Internet Connection Lost..",
				 * "You don't have internet connection.Data Sync Not Completed. Plese Sync Data Again.."
				 * , false);
				 */
			}

		}

	}

	private class DownloadStocks extends AsyncTask<Void, Void, Void> {

		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(DM_InvoiceMenu.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Downloading Stocks Details");
			// Set progressdialog message
			mProgressDialog.setMessage("Loading Stocks Details...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		// *****************Background Process**************************
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			// ******Download Available fItemLoc details**************
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL jsonfItemLoc = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fItemLoc/mobile123"
								+ "/" + serverDbName);
				URLConnection jcfItemLoc = jsonfItemLoc.openConnection();
				BufferedReader readerfItemLoc = new BufferedReader(
						new InputStreamReader(jcfItemLoc.getInputStream()));

				String linefItemLoc = readerfItemLoc.readLine();

				JSONObject jsonResponsefItemLoc = new JSONObject(linefItemLoc);

				JSONArray jsonArrayfItemLoc = jsonResponsefItemLoc
						.getJSONArray("fItemLocResult");
				Log.v(TAG,
						"Array Length fItemLoc :" + jsonArrayfItemLoc.length());

				for (int i = 0; i < jsonArrayfItemLoc.length(); i++) {
					arrayLength = arrayLength + 1;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());

					JSONObject jObjectfItemLoc = (JSONObject) jsonArrayfItemLoc
							.get(i);
					String ItemCodeFI = jObjectfItemLoc.getString("ItemCode");
					String LocCodeFI = jObjectfItemLoc.getString("LocCode");
					String QOHFI = jObjectfItemLoc.getString("QOH");
					RecordIdFI = jObjectfItemLoc.getString("RecordId");
					RecordIdFI = RecordIdFI.trim();
					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfItemLoc = new ContentValues();
					Cursor fItemLocrows = null;
					try {
						String queryfil = "SELECT LocCode,RecordId from fItemLoc Where RecordId ='"
								+ RecordIdFI + "'";
						fItemLocrows = mydb.rawQuery(queryfil, null);
					} catch (Exception e) {
					}
					if (fItemLocrows != null) {
						if (fItemLocrows.getCount() >= 1) {
							Log.v(TAG, "Excisting fItemLocrows 1 :"
									+ RecordIdFI);

							while (fItemLocrows.moveToNext()) {
								Log.v(TAG, "Excisting fItemLocrows 1 :"
										+ RecordIdFI);
								String chkLocCode = fItemLocrows.getString(0);
								String chkRecordId = fItemLocrows.getString(1);

								if (chkLocCode.equals("MS")) {
									Log.v(TAG, "Update fItemLoc QOH: "
											+ chkRecordId);
									newrowfItemLoc.put("QOH", QOHFI.trim());
									mydb.update(ITEM_LOC_DETAILS,
											newrowfItemLoc, "RecordId ='"
													+ chkRecordId + "'", null);
								}
							}

						} else {
							Log.v(TAG, "fItemLoc 1:" + RecordIdFI);
							newrowfItemLoc.put("LocCode", LocCodeFI.trim());
							newrowfItemLoc.put("ItemCode", ItemCodeFI.trim());
							newrowfItemLoc.put("QOH", QOHFI.trim());
							newrowfItemLoc.put("RecordId", RecordIdFI);
							newrowfItemLoc.put("timestamp_column",
									getCurrentTimeString().toString());
							newrowfItemLoc.put("syncRec", "0");
							mydb.insert(ITEM_LOC_DETAILS, null, newrowfItemLoc);
							fItemLocrows.close();
						}
					}
					readerfItemLoc.close();
					mydb.close();
				}

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			// ***************Download fDdbNote*********************************
			// TODO Auto-generated method stub
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceN/PDADBWebServiceRest.svc/fDdbNote/mobile123"
								+ "/" + serverDbName);
				URLConnection jc = json.openConnection();
				BufferedReader readerfDdbNote = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));

				String line = readerfDdbNote.readLine();

				JSONObject jsonResponse = new JSONObject(line);

				JSONArray jsonArrayfDdbNote = jsonResponse
						.getJSONArray("fDdbNoteResult");
				Log.v(TAG,
						"Array Length fDdbNoteResult :"
								+ jsonArrayfDdbNote.length());
				for (int i = 0; i < jsonArrayfDdbNote.length(); i++) {

					JSONObject jObject = (JSONObject) jsonArrayfDdbNote.get(i);
					String AddDate = jObject.getString("AddDate");
					String AddMach = jObject.getString("AddMach");
					String AddUser = jObject.getString("AddUser");
					String Amt = jObject.getString("Amt");
					String BAmt = jObject.getString("BAmt");
					String BTaxAmt = jObject.getString("BTaxAmt");
					String CrAcc = jObject.getString("CrAcc");
					String CurCode = jObject.getString("CurCode");
					String CurRate = jObject.getString("CurRate");
					String DebCode = jObject.getString("DebCode");
					String GlPost = jObject.getString("GlPost");
					String ManuRef = jObject.getString("ManuRef");
					String OvPayAmt = jObject.getString("OvPayAmt");
					String PrtCopy = jObject.getString("PrtCopy");
					String RecordId = jObject.getString("RecordId");
					String RefInv = jObject.getString("RefInv");
					String RefNo = jObject.getString("RefNo");
					String RefNo1 = jObject.getString("RefNo1");
					String Remarks = jObject.getString("Remarks");
					String RepCode = jObject.getString("RepCode");
					String SaleRefNo = jObject.getString("SaleRefNo");
					String TaxAmt = jObject.getString("TaxAmt");
					String TaxComCode = jObject.getString("TaxComCode");
					String TotBal = jObject.getString("TotBal");
					String TotBal1 = jObject.getString("TotBal1");
					String TxnDate = jObject.getString("TxnDate");

					String[] TxnDateFull = TxnDate.split(" ");
					String TxnDateF = TxnDateFull[0];
					// 2/24/2014
					String[] TxnDateFStr = TxnDateF.split("/");
					String txnDateStr = TxnDateFStr[1];
					String txnMonthStr = TxnDateFStr[0];
					String txnYearStr = TxnDateFStr[2];

					if (txnMonthStr.length() == 1) {
						txnMonthStr = "0" + txnMonthStr;
					}
					TxnDate = txnYearStr + "-" + txnMonthStr + "-" + txnDateStr;

					Log.v(TAG, "TxnDate **** :" + TxnDate);

					String TxnType = jObject.getString("TxnType");
					String glbatch = jObject.getString("glbatch");

					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowfDdbNote = new ContentValues();
					Cursor adminuserrows = null;
					try {
						adminuserrows = mydb.query(RECEIPT_INVOICES, null,
								"RefNo ='" + RefNo.trim() + "'", null, null,
								null, null);
					} catch (Exception e) {
					}
					if (adminuserrows != null) {
						if (adminuserrows.getCount() >= 1) {
							while (adminuserrows.moveToNext()) {
								Log.v(TAG, "Excisting adminuserrows 16");
								ContentValues newrowfUpdateDdbNote = new ContentValues();
								String fDDbNoteId = adminuserrows.getString(1);
								newrowfUpdateDdbNote.put("Amt", Amt.trim());
								newrowfUpdateDdbNote.put("BAmt", BAmt.trim());
								newrowfUpdateDdbNote.put("TotBal",
										TotBal.trim());
								newrowfUpdateDdbNote.put("TotBal1",
										TotBal1.trim());
								newrowfUpdateDdbNote.put("TxnDate",
										TxnDate.trim());
								mydb.update(RECEIPT_INVOICES,
										newrowfUpdateDdbNote, "RecordId ='"
												+ fDDbNoteId + "'", null);
							}

						} else {
							Log.v(TAG, "fDdbNote 16:" + RecordId.trim());
							newrowfDdbNote.put("RecordId", RecordId.trim());
							newrowfDdbNote.put("RefNo", RefNo.trim());
							newrowfDdbNote.put("RefInv", RefInv.trim());
							newrowfDdbNote.put("SaleRefNo", SaleRefNo.trim());
							newrowfDdbNote.put("ManuRef", ManuRef.trim());
							newrowfDdbNote.put("TxnType", TxnType.trim());
							newrowfDdbNote.put("TxnDate", TxnDate.trim());
							newrowfDdbNote.put("CurCode", CurCode.trim());
							newrowfDdbNote.put("CurRate", CurRate.trim());
							newrowfDdbNote.put("DebCode", DebCode.trim());
							newrowfDdbNote.put("RepCode", RepCode.trim());
							newrowfDdbNote.put("TaxComCode", TaxComCode.trim());
							newrowfDdbNote.put("TaxAmt", TaxAmt.trim());
							newrowfDdbNote.put("BTaxAmt", BTaxAmt.trim());
							newrowfDdbNote.put("Amt", Amt.trim());
							newrowfDdbNote.put("BAmt", BAmt.trim());
							newrowfDdbNote.put("TotBal", TotBal.trim());
							newrowfDdbNote.put("TotBal1", TotBal1.trim());
							newrowfDdbNote.put("OvPayAmt", OvPayAmt.trim());
							newrowfDdbNote.put("Remarks", Remarks.trim());
							newrowfDdbNote.put("CrAcc", CrAcc.trim());
							newrowfDdbNote.put("PrtCopy", PrtCopy.trim());
							newrowfDdbNote.put("GlPost", GlPost.trim());
							newrowfDdbNote.put("glbatch", glbatch.trim());
							newrowfDdbNote.put("AddUser", AddUser.trim());
							newrowfDdbNote.put("AddDate", AddDate.trim());
							newrowfDdbNote.put("AddMach", AddMach.trim());
							newrowfDdbNote.put("RefNo1", RefNo1.trim());
							mydb.insert(RECEIPT_INVOICES, null, newrowfDdbNote);
							adminuserrows.close();
						}
					}
					mydb.close();
				}

				readerfDdbNote.close();

			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}
			return null;

		}

		@Override
		protected void onPostExecute(Void args) {

			if (NetFail == 0) {
				mProgressDialog.dismiss();
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_InvoiceMenu.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("DOWNLOAD SUCCESS");
				// Setting Dialog Message
				alertDialog.setMessage("Stock Download Completed..");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
			} else if (NetFail == 404) {
				countDownActivator();
			}
			return;
		}

	}

	// handler for the background updating
	Handler progressHandler = new Handler() {
		public void handleMessage(Message msg) {
			mProgressDialog.incrementProgressBy(arrayLength);
		}
	};

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}

	public void checkNetwork() {
		// TODO Auto-generated method stub
		isInternetPresent = cd.isConnectingToInternet();

		// check for Internet status
		if (isInternetPresent) {
			NetFail = 0;
			// Internet Connection is Present
			// make HTTP requests
			Log.v(TAG, "Net Work Present........");
		} else {
			// Internet connection is not present
			Log.v(TAG, "Net Work Disabled........");
			NetFail = 404;
			countDownActivator();
		}
	}

	public void checkNetworkUploading() {
		// TODO Auto-generated method stub
		isInternetPresent = cd.isConnectingToInternet();

		// check for Internet status
		if (isInternetPresent) {
			NetFail = 0;
			// Internet Connection is Present
			// make HTTP requests
			Log.v(TAG, "Net Work Present........");
		} else {
			// Internet connection is not present
			Log.v(TAG, "Net Work Disabled........");
			NetFail = 404;
			networkFailRec = 99;
			countUploadActivator();
		}
	}

	private void countUploadActivator() {
		// TODO Auto-generated method stub
		mCountDown = new CountDownTimer(10000, 1000) {

			@Override
			public void onFinish() {
				mProgressDialog.dismiss();
				arFinvHed.clear();
				arFinvDet.clear();

				arFordHed.clear();
				arFordDet.clear();

				arCanceleInvHedDet.clear();
				arCanceleOrdHedDet.clear();

				arfUnLoadhed.clear();
				arfUnLoadDet.clear();

				arfDRecHed.clear();
				arfDRecDet.clear();

				arfDamHed.clear();
				arfDamDet.clear();

				arFAdjHed.clear();
				arFAdjDet.clear();

				showAlertDialogUpload(
						DM_InvoiceMenu.this,
						"Internet Connection Lost..",
						"Your Internet Connection Lost During Syncing.Data Sync Not Completed. Tap OK to Continue Sync..",
						false);
			}

			@Override
			public void onTick(long millisUntilFinished) {
				Log.v(TAG, "Time Remaining Chk 1:" + millisUntilFinished / 1000);
				isInternetPresent = cd.isConnectingToInternet();

				// check for Internet status
				if (isInternetPresent) {
					NetFail = 0;
					arrayLength = 0;
					// Internet Connection is Present
					// Stop coun down
					mCountDown.cancel();
				} else {
					// Internet connection is not present

				}
			}
		}.start();

	}

	private void countDownActivator() {
		// TODO Auto-generated method stub
		mCountDown = new CountDownTimer(30000, 1000) {

			@Override
			public void onFinish() {
				mProgressDialog.dismiss();
				showAlertDialog(
						DM_InvoiceMenu.this,
						"Internet Connection Lost..",
						"Your Internet Connection Lost During Syncing.Data Sync Not Completed. Tap OK to Continue Sync..",
						false);
			}

			@Override
			public void onTick(long millisUntilFinished) {
				Log.v(TAG, "Time Remaining Chk 1:" + millisUntilFinished / 1000);
				isInternetPresent = cd.isConnectingToInternet();

				// check for Internet status
				if (isInternetPresent) {
					NetFail = 0;
					arrayLength = 0;
					// Internet Connection is Present
					// Stop coun down
					mCountDown.cancel();
				} else {
					// Internet connection is not present

				}
			}
		}.start();

	}

	private String getCurrentTimeString() {
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("dd/MM/yyyy");
		String date_to_string = ddMMMyyFormat.format(dateNow);
		return date_to_string;
	}

	private String getAddDateTimeString() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	/*
	 * public static boolean isExternalStorageReadOnly() { String
	 * extStorageState = Environment.getExternalStorageState(); if
	 * (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) { return
	 * true; } return false; }
	 * 
	 * public static boolean isExternalStorageAvailable() { String
	 * extStorageState = Environment.getExternalStorageState(); if
	 * (Environment.MEDIA_MOUNTED.equals(extStorageState)) { return true; }
	 * return false; }
	 */
}
